Writing to a text file – Java codes
Details:
Name: writeFile.java (Java version: 16.0.1)Description: The code requests user to input a file name to write to. If the file does not exist, it will create a new one. If the file already exists, its content will be overwritten. The code generates a short list of flower names and then write them to the file, line by line. If an error occurs, an error message will appear, and the program will be terminated.
// Writing to a text file
//
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class writeFile {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter file name");
String filename = obj.nextLine(); // read user input for file name
// Create contents to write to file
String str = "My favorite flowers:";
String[] flowers = {"Rose", "Star Jasmine", "Gardenia", "Plumeria"};
//If file does not exist, create new file
try {
File fObj = new File(filename);
if (fObj.createNewFile()) {
System.out.println("File created: " + fObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// write to file
try {
FileWriter myWriter = new FileWriter(filename);
int n=flowers.length;
myWriter.write(str+"\n");
for (int i = 0; i < n; i++) {
myWriter.write(flowers[i]+"\n");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
