I den här artikeln kommer vi att se olika sätt att skriva in i en fil med hjälp av programmeringsspråket Java. Java FileWriter-klassen i java används för att skriva teckenorienterad data till en fil eftersom denna klass är teckenorienterad på grund av vad den används i filhantering i java.
Det är många sätt att skriva in i en fil i Java eftersom det finns många klasser och metoder som kan uppfylla målet enligt följande:
- Använder sig av writeString() metod
- Använder FileWriter Class
- Använder BufferedWriter Class
- Använder FileOutputStream Class
Metod 1: Använd metoden writeString().
Denna metod stöds av Java version 11. Denna metod kan ta fyra parametrar. Dessa är filsökväg, teckensekvens, teckenuppsättning och alternativ. De två första parametrarna är obligatoriska för att denna metod ska kunna skriva in i en fil. Den skriver tecknen som innehållet i filen. Den returnerar filsökvägen och kan skapa fyra typer av undantag. Det är bättre att använda när innehållet i filen är kort.
Exempel: Det visar användningen av writeString() metod som finns under klassen Files för att skriva data till en fil. En annan klass, Path, används för att tilldela filnamnet en sökväg där innehållet kommer att skrivas. Files-klassen har en annan metod som heter readString() för att läsa innehållet i någon befintlig fil som används i koden för att kontrollera att innehållet är korrekt skrivet i filen.
Java
hur får jag reda på min skärmstorlek
// 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);> >}> }> |
>
>Produktion
Welcome to geekforgeeks Happy Learning!>

Metod 2: Använda FileWriter Class
Om innehållet i filen är kort är det ett annat bättre alternativ att använda klassen FileWriter för att skriva i filen. Den skriver också teckenströmmen som innehållet i filen som metoden writeString(). Konstruktören för denna klass definierar standardteckenkodningen och standardbuffertstorleken i byte.
Följande exempel nedan illustrerar användningen av klassen FileWriter för att skriva innehåll i en fil. Det kräver att objektet för FileWriter-klassen skapas med filnamnet för att skriva in i en fil. Därefter används metoden write() för att skriva värdet på textvariabeln i filen. Om något fel uppstår vid tidpunkten för skrivning av filen, kommer ett IOException att kastas, och felmeddelandet kommer att skrivas ut från catch-blocket.
Exempel:
Java
söndra karta
// 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());> >}> >}> }> |
omvandlarsträng till datum
>
>Produktion
File is created successfully with the content.>

Metod 3: Använda BufferedWriter Class
Den används för att skriva text till en teckenutgångsström. Den har en standardbuffertstorlek, men en stor buffertstorlek kan tilldelas. Det är användbart för att skriva tecken, strängar och arrayer. Det är bättre att slå in den här klassen med vilken skrivarklass som helst för att skriva data till en fil om ingen promptutgång krävs.
Exempel:
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());> >}> >}> }> |
>
>Produktion
mac operativsystem
File is created successfully with the content.>

Följande exempel visar användningen av klassen BufferedWriter för att skriva in i en fil. Det kräver också att man skapar objektet i klassen BufferedWriter som FileWriter för att skriva innehåll i filen. Men den här klassen stöder stort innehåll för att skriva in i filen genom att använda en stor buffertstorlek.
Metod 4: Använda FileOutputStream Class
Den används för att skriva råströmdata till en fil. Klasserna FileWriter och BufferedWriter används för att bara skriva texten till en fil, men binära data kan skrivas med hjälp av klassen FileOutputStream.
Att skriva data till en fil med FileOutputStream-klassen visas i följande exempel. Det kräver också att man skapar objektet för klassen med filnamnet för att skriva data till en fil. Här konverteras stränginnehållet till byte-arrayen som skrivs in i filen med hjälp av skriva() metod.
Exempel:
Java
minimax algoritm
// 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());> >}> >}> >}> >}> }> |
>
>Produktion
File is created successfully with the content.>