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(); } }
}
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.
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.
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());
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); } }
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With