Tässä artikkelissa näemme erilaisia tapoja kirjoittaa tiedostoon Java-ohjelmointikielellä. Java FileWriter-luokkaa javassa käytetään merkkipohjaisen datan kirjoittamiseen tiedostoon, koska tämä luokka on merkkipohjainen luokka, koska sitä käytetään Java-tiedoston käsittelyssä.
On olemassa monia tapoja kirjoittaa tiedostoon Javassa koska on monia luokkia ja menetelmiä, jotka voivat täyttää tavoitteen seuraavasti:
- Käyttämällä kirjoitusmerkkijono() menetelmä
- FileWriter-luokan käyttäminen
- BufferedWriter-luokan käyttäminen
- FileOutputStream-luokan käyttäminen
Tapa 1: WriteString()-menetelmän käyttäminen
Java-versio 11 tukee tätä menetelmää. Tämä menetelmä voi sisältää neljä parametria. Nämä ovat tiedostopolku, merkkijono, merkkisarja ja valinnat. Kaksi ensimmäistä parametria ovat pakollisia, jotta tämä menetelmä voi kirjoittaa tiedostoon. Se kirjoittaa merkit tiedoston sisällöksi. Se palauttaa tiedostopolun ja voi antaa neljän tyyppisiä poikkeuksia. On parempi käyttää, kun tiedoston sisältö on lyhyt.
Esimerkki: Se näyttää käytön kirjoitusjono() Tiedostot-luokan alla oleva menetelmä tietojen kirjoittamiseksi tiedostoon. Toista luokkaa, Path, käytetään määrittämään tiedostonimi polkulla, johon sisältö kirjoitetaan. Tiedostot-luokassa on toinen menetelmä nimeltä readString() lukeaksesi minkä tahansa koodissa käytetyn olemassa olevan tiedoston sisällön tarkistaaksesi, että sisältö on kirjoitettu oikein tiedostoon.
Java
linkedlist ja arraylist
// 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);> > }> }> |
>
kuka on freddie mercury
>Lähtö
Welcome to geekforgeeks Happy Learning!>
Tapa 2: FileWriter-luokan käyttäminen
Jos tiedoston sisältö on lyhyt, FileWriter-luokan käyttäminen tiedostoon kirjoittamiseen on toinen parempi vaihtoehto. Se myös kirjoittaa merkkivirran tiedoston sisällöksi, kuten writeString()-menetelmä. Tämän luokan rakentaja määrittää oletusmerkkikoodauksen ja oletuspuskurin koon tavuina.
Seuraava alla oleva esimerkki havainnollistaa FileWriter-luokan käyttöä sisällön kirjoittamiseen tiedostoon. Se edellyttää FileWriter-luokan objektin luomista tiedostonimellä, jotta se voidaan kirjoittaa tiedostoon. Seuraavaksi write()-menetelmää käytetään tekstimuuttujan arvon kirjoittamiseen tiedostoon. Jos tiedoston kirjoittamisen aikana tapahtuu virhe, IOException heitetään ja virhesanoma tulostetaan catch-lohkosta.
Esimerkki:
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());> > }> > }> }> |
>
>Lähtö
listat javassa
File is created successfully with the content.>
Tapa 3: BufferedWriter-luokan käyttäminen
Sitä käytetään tekstin kirjoittamiseen merkkitulostusvirtaan. Sillä on oletuspuskurin koko, mutta suuri puskurikoko voidaan määrittää. Se on hyödyllinen merkkien, merkkijonojen ja taulukoiden kirjoittamiseen. On parempi kääriä tämä luokka mihin tahansa kirjoittajaluokkaan tietojen kirjoittamista varten tiedostoon, jos kehotteita ei vaadita.
Esimerkki:
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());> > }> > }> }> |
>
>Lähtö
tavua merkkijonoon python
File is created successfully with the content.>
Seuraava esimerkki näyttää BufferedWriter-luokan käytön tiedostoon kirjoittamiseen. Se vaatii myös BufferedWriter-luokan objektin, kuten FileWriterin, luomisen sisällön kirjoittamiseksi tiedostoon. Mutta tämä luokka tukee suuren sisällön kirjoittamista tiedostoon käyttämällä suurta puskurikokoa.
Tapa 4: FileOutputStream-luokan käyttäminen
Sitä käytetään kirjoittamaan raakavirtadataa tiedostoon. FileWriter- ja BufferedWriter-luokkia käytetään vain tekstin kirjoittamiseen tiedostoon, mutta binääridataa voidaan kirjoittaa FileOutputStream-luokan avulla.
multiplekseri
Datan kirjoittaminen tiedostoon FileOutputStream-luokan avulla on esitetty seuraavassa esimerkissä. Se edellyttää myös luokan objektin luomista tiedostonimellä tietojen kirjoittamiseksi tiedostoon. Tässä merkkijonon sisältö muunnetaan tavutaulukoksi, joka kirjoitetaan tiedostoon käyttämällä kirjoittaa() menetelmä.
Esimerkki:
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());> > }> > }> > }> > }> }> |
>
>Lähtö
File is created successfully with the content.>