Java NIO 写文件

来源:互联网 发布:linux中echo 编辑:程序博客网 时间:2024/05/16 08:40
//将邮箱 姓名和最后生成的链接数据写入csv文件
    private void writeCsv(String content, String fileName) throws IOException {
        File f = new File(defaultCsvpath);
        f.setWritable(true);
        if (!f.exists()) {  //如果该路径不存在,就创建该路径
            f.mkdir();
        }
        String filePath = defaultCsvpath + "/" + fileName;  //得到完整文件路径
        FileOutputStream fos = null;
        FileChannel fc_out = null;
        try {
            fos = new FileOutputStream(filePath, true);
            fc_out = fos.getChannel();
            ByteBuffer buf = ByteBuffer.wrap(content.getBytes());
            buf.put(content.getBytes());
            buf.flip();
            fc_out.write(buf);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fc_out) {
                fc_out.close();
            }
            if (null != fos) {
                fos.close();
            }
        }
    }