0
点赞
收藏
分享

微信扫一扫

NIO写数据到文件

/**
     * @param file
     * @param context
     * @throws Exception
     */
    public static void writeAdd(String file, String context) {
        FileChannel fc = null;
        RandomAccessFile raf = null;
        try {
            File f = new File(file);
            raf = new RandomAccessFile(f, "rw");
            fc = raf.getChannel();
            fc.position(fc.size());
 
            fc.write(ByteBuffer.wrap(context.getBytes()));
 
            // 关闭文件通道
            raf.close();
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
                fc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
    /**
     * @param file
     * @param context
     * @throws Exception
     */
    public static void writeCover(String file, String context) {
        FileOutputStream fos = null;
        FileChannel fc = null;
        try {
            fos = new FileOutputStream(file);
            // 文件通道
            fc = fos.getChannel();
 
            // 缓冲区数据写入到文件中
            fc.write(ByteBuffer.wrap(context.getBytes()), fc.size());
 
            // 关闭文件通道
            fc.close();
            // 关闭文件输出流
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
 
            try {
                // 关闭文件通道
                fc.close();
                // 关闭文件输出流
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
 
        }
 
    }

举报

相关推荐

0 条评论