2018/05/03 NIO基础使用

前几天写了一个简单的用NIO来生成文件的后台程序。代码如下。

用的FileOutputStream获取的FileCHannel,暂时还不知和RandomAccessFile的区别,暂时了解到后者可以同时进行读写。

暂时是完全重新写入文件,并不是在文件末尾追加信息。

private static final String LINE_SPARATOF = System.getProperty("line.separator");

public static void nioWriteFile(List<String> datas, String fileName) throws IOException {

// 截取获取文件全路径

                String filePath = StrUtil.getFilePath(fileName);

File fileDir = new File(filePath);
if (!fileDir.exists()) {
fileDir.mkdir();
}
FileOutputStream fos = null;
FileChannel outChannel = null;
try {
fos = new FileOutputStream(fileName);
outChannel = fos.getChannel();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < datas.size(); i++) {
sb.append(datas.get(i));
if (i < datas.size() - 1) {
sb.append(LINE_SPARATOF);
}
}
ByteBuffer bb = ByteBuffer.wrap(sb.toString().getBytes("GBK"));
// outChannel.position(outChannel.size());
outChannel.write(bb);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outChannel != null) {
outChannel.close();
}
if (fos != null) {
fos.flush();
fos.close();
}
}
}

猜你喜欢

转载自blog.csdn.net/xlb6179685/article/details/80183328
今日推荐