Jack Armstrong
Jack Armstrong

Reputation: 1249

Reading a File versus Writing One

This question is not specific question, but more a general question. For reading a file I know you can use Scanner and read it and then print it. However reading a file and then printing it in a new format, like double space, indents, basically any spacing issues, is that also considered reading it or is it writing it? From my understanding of what my teacher has taught me, is that writing overwrites the original document and replaces it. Also how does one use the PrintWriter command? I have never seen this before in my class nor have read about it in my textbook but its on my test according to my teacher. Could someone give an explanation and an example about it?

I read this site http://www.caveofprogramming.com/frontpage/articles/java/java-file-reading-and-writing-files-in-java/ on writing files, but it uses FileWriter, which I'm assuming takes the place of scanner? Is that right?

Upvotes: 0

Views: 45

Answers (1)

Zohaib Aslam
Zohaib Aslam

Reputation: 595

reading and writing files in java is all about working with streams and stream may be binary or sequential. java provide different classes in

java.io

package and these classes are used in different scenarios. for example working with binary stream you may need some special functions. PrintWriter classes is used for writing formatted text to text-output stream, as described here PrintWriter

further it is your choice if you want to overwrite existing file or append data to existing file.

here is simple code to write data to a file. you may append or overwrite existing text

import java.io.FileWriter;
import java.io.PrintWriter;

public class Main {
  public static void main(String[] args) throws Exception {
    String filename = "fileName.txt";
    String[] linesToWrite = new String[] { "a", "b" };
    boolean appendToFile = true;

    PrintWriter pw = null;
    if (appendToFile) {
      // if you append data to file then pass 'true' to FileWriter else pass false
      // PrintWriter needs an object of Writer type so we pass an anonymous object of
      // FileWriter to PrintWriter constructor
      pw = new PrintWriter(new FileWriter(filename, true));
    } else {
      pw = new PrintWriter(new FileWriter(filename));
      // pw = new PrintWriter(new FileWriter(filename, false));
    }
    for (int i = 0; i < linesToWrite.length; i++) {
      pw.println(linesToWrite[i]);
    }
    pw.flush();
    pw.close();
  }
}

Upvotes: 1

Related Questions