File represent either the name of a particular file or the names of a set of files in a directory. Use Scanner class for reading text files.
Methods common to all input streams:
1 int read() throws IOException 2 //reads one byte (character) of data 3 void reset() throws IOException 4 //starts stream over so its bytes can be read again 5 void close() throws IOException 6 //notifies stream you are finished using itMethods common to all output streams:
1 void write(int n) throws IOException 2 //writes one byte (character) of data 3 void flush() throws IOException 4 //writes any bytes that were waiting to be written 5 void close() throws IOException 6 //notifies stream you are finished using it1、This is a bridge between bytes and chars. 2、The read() method returns an int, which must be cast to a char. 3、read() returns -1 if the end of the stream has been reached. Thus the program above will never stop, since we can’t type the “end-of-stream” value.
System.in: byte stream
1 public static void main(String[] args) { 2 InputStreamReader isr = new InputStreamReader(System.in); 3 int c; 4 try { 5 while ((c = isr.read()) != -1) 6 System.out.println((char) c); 7 } catch(IOException e) { 8 //… 9 } 10 } 1 public static void main(String[] args) throws IOException { 2 InputStreamReader isr = new InputStreamReader(new FileInputStream("FileInput.java")); 3 int c; 4 while ((c = isr.read()) != -1) 5 System.out.println((char) c); 6 isr.close(); 7 }also:
1 BufferedReader br2 = new BufferedReader(new FileReader(“hardcode.txt”)); 2 String anotherLine = br2.readLine(); 3 br2.close();1、To write to a file, construct a PrintWriter object: PrintWriter out = new PrintWriter("out.txt"); 2、If file already exists, it is emptied before the new data are written into it. 3、If file doesn’t exist, an empty file is created. 4、Use print and println to write into a PrintWriter: out.println("Hello, World!"); out.printf("Total: %8.2f\n", total); 5、You must close a file when you are done processing it: in.close(); out.close();Otherwise, not all of the output may be written to the disk file. 6、Always specify “UTF-8” as the second parameter when construction a Scanner or a PrintWriter.
Instance variables that you do not wish to save (or can’t save, because they are not serializable) can be declared with transient modifier (or static) private transient TextReader in;
