java缓冲流BufferWriter的原理跟提高效率原因
2个回答
展开全部
使用BufferedWriter写入文本时不用将文本转换成字节数组,直接整行整行的写入,大大提供了写入效率。
在下面的示例代码中向文件中写入两行文本。
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author gdb
*/
public class Main {
/**
* Prints some data to a file using a BufferedWriter
*/
public void writeToFile(String filename) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
bufferedWriter.newLine();
bufferedWriter.write("Writing line two to file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writeToFile("myFile.txt");
}
}
执行上述代码后文件中的文本如下:
Writing line one to file
Writing line two to file
注意使用BufferedWriter一定要在finally中flush()并close().
在下面的示例代码中向文件中写入两行文本。
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author gdb
*/
public class Main {
/**
* Prints some data to a file using a BufferedWriter
*/
public void writeToFile(String filename) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
bufferedWriter.newLine();
bufferedWriter.write("Writing line two to file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writeToFile("myFile.txt");
}
}
执行上述代码后文件中的文本如下:
Writing line one to file
Writing line two to file
注意使用BufferedWriter一定要在finally中flush()并close().
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询