Java – 附加到文件

Java – 附加到文件

原文: https://howtodoinjava.com/java/io/java-append-to-file/

使用BufferedWritterPrintWriterFileOutputStreamFiles类学习将内容追加到 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附加到文件

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附加到文件

使用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将二进制数据写入文件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类附加到文件

使用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
}

学习愉快!