在本教程中,我们将学习如何使用 Java 将内容附加到文件中。有两种方法可以追加:
1)使用FileWriter
和BufferedWriter
:在这种方法中,我们将在一个或多个字符串中包含内容,我们将把这些字符串附加到文件中。该文件可以单独使用FileWriter
附加,但使用BufferedWriter
可以在维护缓冲区时提高性能。
2)使用PrintWriter
:这是将内容附加到文件的最佳方式之一。无论你使用PrintWriter
对象写什么都会附加到文件中。
使用FileWriter
和BufferedWriter
将内容附加到File
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo
{
public static void main( String[] args )
{
try{
String content = "This is my content which would be appended " +
"at the end of the specified file";
//Specify the file name and path here
File file =new File("C://myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if(!file.exists()){
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
输出:
Data successfully appended at the end of file
让我们说myfile.txt
的内容是:
This is the already present content of my file
运行上述程序后,内容将是:
This is the already present content of my fileThis is my content which
would be appended at the end of the specified file
使用PrintWriter
将内容附加到File
PrintWriter
为您提供更大的灵活性。使用此功能,您可以轻松格式化要附加到File
的内容。
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo2
{
public static void main( String[] args )
{
try{
File file =new File("C://myfile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended at the end of file");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
输出:
Data successfully appended at the end of file
让我们说myfile.txt
的内容是:
This is the already present content of my file
运行上述程序后,内容将是:
This is the already present content of my file
This is first line
This is the second line
This is third line