什么是Java NIO中BufferedWriter的替代方案

时间:2016-04-01 07:38:35

标签: java nio filechannel

如果我们使用Java Standard IO api来逐行读取文件并操纵行并将其写入新文件。我们会使用这样的代码片段。

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String str;
while ((str = br.readLine()) != null) {
    //... code for manipulation of str
    bw.write(str);
    bw.newLine();
}

我需要对正在编写的文件执行readlock,所以我继续在Java NIO包中使用FileChannel。为了达到同样的目的。我写的代码片段如下。

int blocksize = 32 * 1024;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilePath), inputCharset));
FileOutputStream fos = new FileOutputStream(outputFilePath);
FileChannel outputFileChannel = fos.getChannel();
outputFileChannel.lock();
ByteBuffer buffer = ByteBuffer.allocate(blocksize);
while((line=br.readLine())!=null){
    buffer.put(line.getBytes(StandardCharsets.UTF_8));
    buffer.put("\n".getBytes(StandardCharsets.UTF_8));
    buffer.flip();
    outputFileChannel.write(buffer);
    buffer.clear();
}
br.close();
outputFileChannel.close();
fos.close(); 

现在我的问题是这对性能有多大影响,每当我们调用 filechannel.write 时,Filechannel会写入文件(我的意思是它的行为与filereader.write完全相同)还是会内部使用缓冲区。

1 个答案:

答案 0 :(得分:2)

我会使用BufferedWriter和FileChannel.lock()。

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
FileLock lock = fis.getChannel().lock();

BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String str;
while ((str = br.readLine()) != null) {
    //... code for manipulation of str
    bw.write(str);
    bw.newLine();
}
lock.release();