En este tutorial aprenderemos cómo agregar contenido a un archivo en Java. Hay dos formas de agregar:
1) Utilizando FileWriter
es BufferedWriter
: En este enfoque, tendremos el contenido en una o más cadenas y las agregaremos al archivo. El archivo se puede agregar usando FileWriter
solo sin embargo usando BufferedWriter
mejora el rendimiento ya que mantiene un búfer.
2) Utilizando PrintWriter
: Esta es una de las mejores formas de agregar contenido a un archivo. Lo que sea que escribas usando PrintWriter
el objeto se agregaría al archivo.
1) Agregue contenido al archivo usando FileWriter y BufferedWriter
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(); } } }
Producción:
Data successfully appended at the end of file
Digamos que el contenido de myfile.txt fue:
This is the already present content of my file
Después de ejecutar el programa anterior, el contenido sería:
This is the already present content of my fileThis is my content which would be appended at the end of the specified file
2) Agregue contenido al archivo usando PrintWriter
PrintWriter
te da más flexibilidad. Con esto, puede formatear fácilmente el contenido que debe agregarse al archivo 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(); } } }
Producción:
Data successfully appended at the end of file
Digamos que el contenido de myfile.txt fue:
This is the already present content of my file
Después de ejecutar el programa anterior, el contenido sería:
This is the already present content of my file This is first line This is the second line This is third line