En este artículo, veremos diferentes formas de escribir en un archivo utilizando el lenguaje de programación Java. La clase Java FileWriter en Java se usa para escribir datos orientados a caracteres en un archivo, ya que esta clase está orientada a caracteres debido a lo que se usa en el manejo de archivos en Java.
Hay muchos formas de escribir en un archivo en Java ya que existen muchas clases y métodos que pueden cumplir el objetivo de la siguiente manera:
- Usando escribirCadena() método
- Usando la clase FileWriter
- Usando la clase BufferedWriter
- Usando la clase FileOutputStream
Método 1: usar el método writeString()
Este método es compatible con la versión 11 de Java. Este método puede tomar cuatro parámetros. Estos son la ruta del archivo, la secuencia de caracteres, el juego de caracteres y las opciones. Los primeros dos parámetros son obligatorios para que este método escriba en un archivo. Escribe los caracteres como contenido del archivo. Devuelve la ruta del archivo y puede generar cuatro tipos de excepciones. Es mejor utilizarlo cuando el contenido del archivo es breve.
Ejemplo: Muestra el uso de la escribirCadena() método que se encuentra bajo la clase Archivos para escribir datos en un archivo. Otra clase, Path, se utiliza para asignar al nombre del archivo una ruta donde se escribirá el contenido. La clase de archivos tiene otro método llamado leerCadena() leer el contenido de cualquier archivo existente que se utilice en el código para verificar que el contenido esté escrito correctamente en el archivo.
Java
comentario multilínea powershell
// Java Program to Write Into a File> // using writeString() Method> // Importing required classes> import> java.io.IOException;> import> java.nio.file.Files;> import> java.nio.file.Path;> // Main class> public> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >throws> IOException> >{> >// Assigning the content of the file> >String text> >=>'Welcome to geekforgeeks
Happy Learning!'>;> >// Defining the file name of the file> >Path fileName = Path.of(> >'/Users/mayanksolanki/Desktop/demo.docx'>);> >// Writing into the file> >Files.writeString(fileName, text);> >// Reading the content of the file> >String file_content = Files.readString(fileName);> >// Printing the content inside the file> >System.out.println(file_content);> >}> }> |
>
>Producción
Welcome to geekforgeeks Happy Learning!>

aprender selenio
Método 2: usar la clase FileWriter
Si el contenido del archivo es corto, entonces usar la clase FileWriter para escribir en el archivo es otra mejor opción. También escribe el flujo de caracteres como contenido del archivo, como el método writeString(). El constructor de esta clase define la codificación de caracteres predeterminada y el tamaño del búfer predeterminado en bytes.
El siguiente ejemplo ilustra el uso de la clase FileWriter para escribir contenido en un archivo. Requiere crear el objeto de la clase FileWriter con el nombre del archivo para escribir en un archivo. A continuación, se utiliza el método write() para escribir el valor de la variable de texto en el archivo. Si se produce algún error al momento de escribir el archivo, se generará una IOException y el mensaje de error se imprimirá desde el bloque catch.
Ejemplo:
Java
programación java de números primos
// Java Program to Write into a File> // using FileWriterClass> // Importing required classes> import> java.io.FileWriter;> import> java.io.IOException;> // Main class> public> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Content to be assigned to a file> >// Custom input just for illustration purposes> >String text> >=>'Computer Science Portal techcodeview.com'>;> >// Try block to check if exception occurs> >try> {> >// Create a FileWriter object> >// to write in the file> >FileWriter fWriter =>new> FileWriter(> >'/Users/mayanksolanki/Desktop/demo.docx'>);> >// Writing into file> >// Note: The content taken above inside the> >// string> >fWriter.write(text);> >// Printing the contents of a file> >System.out.println(text);> >// Closing the file writing connection> >fWriter.close();> >// Display message for successful execution of> >// program on the console> >System.out.println(> >'File is created successfully with the content.'>);> >}> >// Catch block to handle if exception occurs> >catch> (IOException e) {> >// Print the exception> >System.out.print(e.getMessage());> >}> >}> }> |
>
>Producción
File is created successfully with the content.>

Método 3: uso de la clase BufferedWriter
Se utiliza para escribir texto en una secuencia de salida de caracteres. Tiene un tamaño de búfer predeterminado, pero se puede asignar un tamaño de búfer grande. Es útil para escribir caracteres, cadenas y matrices. Es mejor combinar esta clase con cualquier clase de escritor para escribir datos en un archivo si no se requiere una salida rápida.
Ejemplo:
Java
// Java Program to write into a File> // Using BufferedWriter Class> // Importing java input output libraries> import> java.io.BufferedWriter;> import> java.io.FileWriter;> import> java.io.IOException;> // Main class> public> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Assigning the file content> >// Note: Custom contents taken as input to> >// illustrate> >String text> >=>'Computer Science Portal techcodeview.com'>;> >// Try block to check for exceptions> >try> {> >// Step 1: Create an object of BufferedWriter> >BufferedWriter f_writer> >=>new> BufferedWriter(>new> FileWriter(> >'/Users/mayanksolanki/Desktop/demo.docx'>));> >// Step 2: Write text(content) to file> >f_writer.write(text);> >// Step 3: Printing the content inside the file> >// on the terminal/CMD> >System.out.print(text);> >// Step 4: Display message showcasing> >// successful execution of the program> >System.out.print(> >'File is created successfully with the content.'>);> >// Step 5: Close the BufferedWriter object> >f_writer.close();> >}> >// Catch block to handle if exceptions occurs> >catch> (IOException e) {> >// Print the exception on console> >// using getMessage() method> >System.out.print(e.getMessage());> >}> >}> }> |
>
>Producción
para cada texto mecanografiado
File is created successfully with the content.>

El siguiente ejemplo muestra el uso de la clase BufferedWriter para escribir en un archivo. También requiere crear el objeto de la clase BufferedWriter como FileWriter para escribir contenido en el archivo. Pero esta clase admite contenido grande para escribir en el archivo utilizando un tamaño de búfer grande.
Método 4: usar la clase FileOutputStream
Se utiliza para escribir datos de flujo sin procesar en un archivo. Las clases FileWriter y BufferedWriter se usan para escribir solo el texto en un archivo, pero los datos binarios se pueden escribir usando la clase FileOutputStream.
En el siguiente ejemplo se muestra cómo escribir datos en un archivo usando la clase FileOutputStream. También requiere crear el objeto de la clase con el nombre de archivo para escribir datos en un archivo. Aquí, el contenido de la cadena se convierte en la matriz de bytes que se escribe en el archivo mediante el método escribir() método.
Ejemplo:
Java
nodo de lista java
// Java Program to Write into a File> // using FileOutputStream Class> // Importing java input output classes> import> java.io.FileOutputStream;> import> java.io.IOException;> public> class> GFG {> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Assign the file content> >String fileContent =>'Welcome to geeksforgeeks'>;> >FileOutputStream outputStream =>null>;> >// Try block to check if exception occurs> >try> {> >// Step 1: Create an object of FileOutputStream> >outputStream =>new> FileOutputStream(>'file.txt'>);> >// Step 2: Store byte content from string> >byte>[] strToBytes = fileContent.getBytes();> >// Step 3: Write into the file> >outputStream.write(strToBytes);> >// Print the success message (Optional)> >System.out.print(> >'File is created successfully with the content.'>);> >}> >// Catch block to handle the exception> >catch> (IOException e) {> >// Display the exception/s> >System.out.print(e.getMessage());> >}> >// finally keyword is used with in try catch block> >// and this code will always execute whether> >// exception occurred or not> >finally> {> >// Step 4: Close the object> >if> (outputStream !=>null>) {> >// Note: Second try catch block ensures that> >// the file is closed even if an error> >// occurs> >try> {> >// Closing the file connections> >// if no exception has occurred> >outputStream.close();> >}> >catch> (IOException e) {> >// Display exceptions if occurred> >System.out.print(e.getMessage());> >}> >}> >}> >}> }> |
>
>Producción
File is created successfully with the content.>