logo

Programa Java per escriure en un fitxer

En aquest article, veurem diferents maneres d'escriure en un fitxer mitjançant el llenguatge de programació Java. La classe Java FileWriter a Java s'utilitza per escriure dades orientades a caràcters en un fitxer, ja que aquesta classe és una classe orientada a caràcters a causa del que s'utilitza en el maneig de fitxers a Java.

Hi ha molts maneres d'escriure en un fitxer en Java ja que hi ha moltes classes i mètodes que poden complir l'objectiu de la següent manera:

  1. Utilitzant writeString() mètode
  2. Utilitzant la classe FileWriter
  3. Utilitzant la classe BufferedWriter
  4. Utilitzant la classe FileOutputStream

Mètode 1: utilitzant el mètode writeString().

Aquest mètode és compatible amb la versió 11 de Java. Aquest mètode pot prendre quatre paràmetres. Aquests són el camí del fitxer, la seqüència de caràcters, el conjunt de caràcters i les opcions. Els dos primers paràmetres són obligatoris perquè aquest mètode escrigui en un fitxer. Escriu els caràcters com el contingut del fitxer. Retorna la ruta del fitxer i pot llançar quatre tipus d'excepcions. És millor utilitzar-lo quan el contingut del fitxer és curt.



Exemple: Mostra l'ús de la writeString() mètode que es troba a la classe Files per escriure dades en un fitxer. Una altra classe, Path, s'utilitza per assignar el nom del fitxer amb una ruta on s'escriurà el contingut. La classe Files té un altre mètode anomenat readString() per llegir el contingut de qualsevol fitxer existent que s'utilitza al codi per comprovar que el contingut està correctament escrit al fitxer.

Java


diferència entre l'arbre binari i l'arbre de cerca binari



// 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);> >}> }>

>

>

Sortida

Welcome to geekforgeeks Happy Learning!>

Mètode 2: Ús de la classe FileWriter

Si el contingut del fitxer és curt, utilitzar la classe FileWriter per escriure al fitxer és una altra opció millor. També escriu el flux de caràcters com el contingut del fitxer com el mètode writeString(). El constructor d'aquesta classe defineix la codificació de caràcters per defecte i la mida de la memòria intermèdia per defecte en bytes.

terminal kali linux

L'exemple següent il·lustra l'ús de la classe FileWriter per escriure contingut en un fitxer. Requereix crear l'objecte de la classe FileWriter amb el nom del fitxer per escriure en un fitxer. A continuació, s'utilitza el mètode write() per escriure el valor de la variable de text al fitxer. Si es produeix algun error en el moment d'escriure el fitxer, es llançarà una IOException i el missatge d'error s'imprimirà des del bloc catch.

Exemple:

Java




// 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());> >}> >}> }>

matemàtiques rodones java
>

>

Sortida

File is created successfully with the content.>

Mètode 3: Ús de la classe BufferedWriter

S'utilitza per escriure text en un flux de sortida de caràcters. Té una mida de memòria intermèdia predeterminada, però es pot assignar una mida de memòria intermèdia gran. És útil per escriure caràcters, cadenes i matrius. És millor embolicar aquesta classe amb qualsevol classe d'escriptor per escriure dades en un fitxer si no es requereix una sortida de sol·licitud.

Exemple:

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());> >}> >}> }>

>

>

Sortida

java lambda
File is created successfully with the content.>

L'exemple següent mostra l'ús de la classe BufferedWriter per escriure en un fitxer. També requereix crear l'objecte de la classe BufferedWriter com FileWriter per escriure contingut al fitxer. Però aquesta classe admet contingut gran per escriure al fitxer utilitzant una mida de memòria intermèdia gran.

Mètode 4: Ús de la classe FileOutputStream

S'utilitza per escriure dades de flux en brut en un fitxer. Les classes FileWriter i BufferedWriter s'utilitzen per escriure només el text en un fitxer, però les dades binàries es poden escriure mitjançant la classe FileOutputStream.

Per escriure dades en un fitxer mitjançant la classe FileOutputStream es mostra a l'exemple següent. També requereix crear l'objecte de la classe amb el nom del fitxer per escriure dades en un fitxer. Aquí, el contingut de la cadena es converteix en la matriu de bytes que s'escriu al fitxer mitjançant l' escriure () mètode.

Exemple:

Java




dijkstra
// 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());> >}> >}> >}> >}> }>

>

>

Sortida

File is created successfully with the content.>