使用BufferedWritter
,PrintWriter
,FileOutputStream
和Files
类学习将内容追加到 Java 中的文件。 在所有示例中,在打开要写入的文件时,您都传递了第二个参数true
,该参数表示以附加模式打开了文件。
Table of Contents
Append to File using BufferedWritter
Append to File using PrintWriter
Append to File using FileOutputStream
Append to File using Files class
BufferedWritter
会在写入之前进行缓冲,因此会减少的 IO 操作的数量,从而提高性能。
要将内容附加到现有文件,请通过将第二个参数传递为true
,以附加模式打开文件编写器。
public static void usingBufferedWritter() throws IOException
{
String textToAppend = "Happy Learning !!";
BufferedWriter writer = new BufferedWriter(
new FileWriter("c:/temp/samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(textToAppend);
writer.close();
}
使用PrintWriter
将格式化的文本写入文件。 此类实现PrintStream
中提供的所有打印方法,因此您可以使用System.out.println()
语句使用的所有格式。
要将内容追加到现有文件中,请通过将第二个参数传递为true
来以追加模式打开文件编写器。
public static void usingPrintWriter() throws IOException
{
String textToAppend = "Happy Learning !!";
FileWriter fileWriter = new FileWriter("c:/temp/samplefile.txt", true); //Set true for append mode
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println(textToAppend); //New line
printWriter.close();
}
使用FileOutputStream
将二进制数据写入文件。 FileOutputStream
用于写入原始字节流,例如图像数据。 要编写字符流,请考虑使用FileWriter
。
要将内容追加到现有文件中,请通过将第二个参数作为true
传递,以追加模式打开FileOutputStream
。
public static void usingFileOutputStream() throws IOException
{
String textToAppend = "\r\n Happy Learning !!"; //new line in content
FileOutputStream outputStream = new FileOutputStream("c:/temp/samplefile.txt", true);
byte[] strToBytes = textToAppend.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
使用Files
类,我们可以使用write
函数编写文件,在内部使用OutputStream
将字节数组写入文件。
要将内容追加到现有文件中,请在写入内容时使用StandardOpenOption.APPEND
。
public static void usingPath() throws IOException
{
String textToAppend = "\r\n Happy Learning !!"; //new line in content
Path path = Paths.get("c:/temp/samplefile.txt");
Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND); //Append mode
}
学习愉快!