In: Computer Science
Please write a java program to write to a text file and to read from a text file.
//WriteToFile.java
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class WriteToFile {
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file name to write data:");
String fileName = scanner.nextLine();
System.out.println("Enter data:");
String data = scanner.nextLine();
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.write(data);
writer.close();
}
}
////////////////////////////////////////////////////////////
import java.io.*;
import java.util.Scanner;
public class ReadText {
public static void main(String[] args) throws IOException {
String fileName;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter file name: ");
fileName = scanner.nextLine();
File file = new File(fileName);
try {
// open the file
Scanner scan = new Scanner(file);
// if file has contents to read
// loop to read the contents of the file
String s;
while(scan.hasNext()) {
s = scan.nextLine()+" ";
System.out.println(s);
}
scan.close();
// close the Scanner object
} catch (FileNotFoundException e) {
// catch the exception if file not present
System.out.println("File " + file.getName() + " not present ");
System.exit(0);
}
}
}