Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to write a text file in Java?

Tags:

java

file

text

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

I searched the web and found this code, but I understand 50% of it.

import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException;  public class WriteToFileExample { public static void main(String[] args) {     try {          String content = "This is the content to write into file";          File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");          // if file doesnt exists, then create it         if (!file.exists()) {             file.createNewFile();         }          FileWriter fw = new FileWriter(file.getAbsoluteFile());         BufferedWriter bw = new BufferedWriter(fw);         bw.write(content);         bw.close();          System.out.println("Done");      } catch (IOException e) {         e.printStackTrace();     } } 

}

like image 642
Georgi Koemdzhiev Avatar asked Apr 04 '14 09:04

Georgi Koemdzhiev


People also ask

How do I write to a text file in Java 8?

FileWriter + BufferedWriter 3.2 In Java 8, we can use the Files. newBufferedWriter to directly create a BufferedWriter object. P.S There is nothing wrong with the above FileWriter + BufferedWriter method to write a file, just the Files. write provides more clean and easy to use API.

What class gives an easy way to write data to files?

Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java.


2 Answers

With Java 7 and up, a one liner using Files:

String text = "Text to save to file"; Files.write(Paths.get("./fileName.txt"), text.getBytes()); 
like image 164
dazito Avatar answered Sep 26 '22 06:09

dazito


You could do this by using JAVA 7 new File API.

code sample: `

public class FileWriter7 {     public static void main(String[] args) throws IOException {         List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });         String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";         writeSmallTextFile(lines, filepath);     }      private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {         Path path = Paths.get(aFileName);         Files.write(path, aLines, StandardCharsets.UTF_8);     } } 

`

like image 44
Dilip Kumar Avatar answered Sep 26 '22 06:09

Dilip Kumar