This tutorial will guide you through on how to read ASCII files in Java language:
To read from a file:
PHP Code:
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
String line = br.readLine(); // this will be the first line in the file
while (line != null) {
// logic on what to do when line is read
// is here
line = br.readLine(); // iterating lines throughout the files
}
br.close(); // close your buffer
To write a file:
PHP Code:
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
pw.println("Hello World!"); // Hello World! will be printed in the file
pw.flush(); // flush buffer to print
pw.close(); // close PrintWriter
Don't forget to import
BufferedReader,
FileReader,
PrintWriter, and
FileWriter. I'm assuming that you know where to put these lines of code. BufferedReader will throws an exception of FileNotFoundException and PrintWriter will throws IOException. So you probably need to handle those as well
PHP Code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
Hopefully this tutorial helps everybody
