【发布时间】:2011-09-09 19:01:50
【问题描述】:
我需要使用 java nio 将巨大的字符串写入(附加)到平面文件。编码为 ISO-8859-1。
目前我们正在编写如下所示。有没有更好的方法来做同样的事情?
public void writeToFile(Long limit) throws IOException{
String fileName = "/xyz/test.txt";
File file = new File(fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = null;
String messageToWrite = null;
for(int i=1; i<limit; i++){
//messageToWrite = get String Data From database
byteBuffer = ByteBuffer.wrap(messageToWrite.getBytes(Charset.forName("ISO-8859-1")));
fileChannel.write(byteBuffer);
}
fileChannel.close();
}
编辑:尝试了这两个选项。以下是结果。
@Test
public void testWritingStringToFile() {
DiagnosticLogControlManagerImpl diagnosticLogControlManagerImpl = new DiagnosticLogControlManagerImpl();
try {
File file = diagnosticLogControlManagerImpl.createFile();
long startTime = System.currentTimeMillis();
writeToFileNIOWay(file);
//writeToFileIOWay(file);
long endTime = System.currentTimeMillis();
System.out.println("Total Time is " + (endTime - startTime));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param limit
* Long
* @throws IOException
* IOException
*/
public void writeToFileNIOWay(File file) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = null;
String messageToWrite = null;
for (int i = 1; i < 1000000; i++) {
messageToWrite = "This is a test üüüüüüööööö";
byteBuffer = ByteBuffer.wrap(messageToWrite.getBytes(Charset
.forName("ISO-8859-1")));
fileChannel.write(byteBuffer);
}
}
/**
*
* @param limit
* Long
* @throws IOException
* IOException
*/
public void writeToFileIOWay(File file) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
fileOutputStream, 128 * 100);
String messageToWrite = null;
for (int i = 1; i < 1000000; i++) {
messageToWrite = "This is a test üüüüüüööööö";
bufferedOutputStream.write(messageToWrite.getBytes(Charset
.forName("ISO-8859-1")));
}
bufferedOutputStream.flush();
fileOutputStream.close();
}
private File createFile() throws IOException {
File file = new File(FILE_PATH + "test_sixth_one.txt");
file.createNewFile();
return file;
}
使用 ByteBuffer 和 Channel:耗时 4402 毫秒
使用缓冲写入器:耗时 563 毫秒
【问题讨论】:
-
我认为至少还有三种方法可以在 Java 中将字符串写入文本文件。尝试在 SO 中搜索,有很多答案可以满足您的需求:)
-
@evilone。我理解有很多方法。如果人们拥有这些知识并且不介意分享,我不想测试所有可能的方法并进行分析并重新发明轮子。
-
@nobody。 “更好”是什么意思?快点?清洁器?就个人而言,我会遵循可读性路径并使用普通的 IO PrintWritter。你为什么要选择蔚来?
-
NIO 不会“将内存占用卸载到操作系统”。而且它肯定不会比你使用它的 BufferedWriter 快。
-
更新:在Java 11中,只需使用Files.writeString一行即可。
标签: java file-io character-encoding nio