Tuesday, February 22, 2011

Java how to read a file line by line

I keep forgetting and I keep having to google it up...

public class MyFileReader {
 File file;
 FileReader fr;
 BufferedReader br = null;

 public MyFileReader(File f) throws FileNotFoundException {
  file = f;
  fr = new FileReader(file);
  br = new BufferedReader(fr);
 }

 public void readAll() throws IOException {
  String line;
  while ( (line = br.readLine()) != null ) {

   System.out.println(line);
  }

 }

 public void close() {
  br.close();
  fr.close();
 }
}





How to write a file:

   FileWriter fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
    out.write("I Love Silvio (just kidding)");
    out.close();


No comments: