Java file I/O(java 文件輸入輸出)


File Overview

I/O = Input/Output, here it is input to and output from programs

  Inputs can be from: Keyboard Files Etc.

  Output can be: Screen Files Etc.

Advantages of file I/O

-permanent copy

-output from one program can be input to another

-input can be automated (rather than entered manually)

Streams

  Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) it acts as a buffer between the data source and destination

  Input stream: a stream that provides input to a program E.g., System.in is an input stream

  Output stream: a stream that accepts output from a program E.g., System.out is an output stream

  Examples: System.out.println(“Hi”)    connects a program to the screen

Streams作為電子設備與程序傳輸過程中的傳輸工具

 

Binary vs. Text Files

  All data and programs are ultimately just zeros and ones each digit can have one of two values (0 or 1),

  hence binary 1 byte = 8 bits

  Text files: the bits represent printable characters

  one byte per character for ASCII, the most common code

  for example, Java source files are text files so is any file created with a "text editor"

  Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data

Text Files vs. Binary Files

  Numbe r: 127 (decimal)十進制

  Text file Three bytes: “1”, “2”, “7” ASCII (decimal): 49, 50, 55

  ASCII (binary): 00110001, 00110010, 00110111

  Binary file: One byte (byte): 01111111     Two bytes (short): 00000000 01111111    Four bytes (int): 00000000 00000000 00000000 01111111

Buffering

  Not buffered: each byte is read/written from/to disk as soon as possible “little” delay for each byte A disk operation per byte--- higher overhead

  Buffered: reading/writing in “chunks” Some delay for some bytes,

   e.g.: Assume 16-byte buffers

  Reading: access the first 4 bytes, need to wait for all 16 bytes are read from disk to memory

  Writing: save the first 4 bytes, need to wait for all 16 bytes before writing from memory to disk

  A disk operation per a buffer of bytes---lower overhead

 

Java I/O

  Standard IO: System.out.println("a line"); to send a line to the standard output, i.e., the screen, unless you redirect standard output

  public class RedirectSysOut {//重定向輸出

    public static void main(String[] args) throws FileNotFoundException { //文件找不到時要拋出異常

    PrintStream stream1 = System.out;     //新建一個打印對象

    File aFile=new File("sysout.log");

    PrintStream stream2 = new PrintStream(new FileOutputStream(aFile));

    System.out.println("1");

    System.setOut(stream2);   //重定項屏幕輸出到stream2對象中

    System.out.println("2");

    System.setOut(stream1);

    System.out.println("3");

    }

  }

 

Text File I/O

  Important classes for text file output (to the file)

   1)FileWriter

   2)FileOutputStream

   3)BufferedWriter

   4)PrintWriter

  Important classes for text file input (from the file):

   1)FileReader

   2)BufferedReader

  FileWriter and FileReader take file names as arguments.

  PrintWriter and BufferedReader provide useful methods for easier writing and reading.

                                              

 

對 TXT 文件的輸入輸出,使用 FileReader和FileWriter。

 

 

                                

因為PrintWriter的范圍最大,所以使用起來也最方便??

 

 

Text File Output

To open a text file for output: connect a text file to a stream for writing FileOutputStream

  fOutStream = new FileOutputStream("out.txt");

  PrintWriter pWriter = new PrintWriter(fOutStream );

Or:

  PrintWriter outputStream = new PrintWriter(new FileOutputStream("out.txt"));

  What happened is: create a PrintWriter object which uses FileOutputStream to open a text file FileOutputStream “connects” PrintWriter to a text file.

    

exa:

  public static void main(String[] args) {

    PrintWriter outputStream = null;

    try {

      outputStream = new PrintWriter(new FileOutputStream("out.txt"));  //open the file

      for (int count = 1; count <= 3; count++)

        outputStream.println(count); //write the file

      System.out.println("... written to out.txt.");

      outputStream.close();

     } catch(FileNotFoundException e){

       System.out.println("Error opening the file out.txt."+ e.getMessage());

       }

     }

   }

 

Overwriting a File

  In the previous example:

    -Opening an output file creates a new file if it does not already exist

    - If the file is existing,it will overwrite the file, i.e., data in the original file is lost

 

因為之前都是overwrite

Appending to a Text File

  To add/append to a file instead of replacing it, use a different constructor for FileOutputStream:

    outputStream = new PrintWriter(new FileOutputStream("out.txt", true));

 

    outputStream = new PrintWriter(new FileOutputStream("out.txt”));

    for (int count = 1; count <= 10; count++)

      outputStream.println(count);

    outputStream.close();

    outputStream = new PrintWriter(new FileOutputStream("out.txt”, true));

     for (int count = 1; count <= 10; count++)

      outputStream.println(count);

    outputStream.close();

 

Closing a File

  After writing a file, you should close the FileOutputStream and the PrintWriter

  fileOutputStream.close();

  outputStream.close();

-Why close the file?

  To make sure it is closed if a program ends abnormally (it could get damaged if it is left open) Flush the stream Calling close() on a wrapper stream should close the child stream.  E.g., if a PrintWriter is closed, the FileOutputStream it linked with is also closed.

-outputStream.close();

  Both the PrintWriter and FileOutputStream have been closed!!!  程序是通過PrintWriter——》FileOutputStream 接觸到TXT(比如),如果關閉了 FileOutputStream 就直接斷開了程序與文件的聯系,就等於兩者都關閉了。

 

 

 

 

 

 

 

Text File Input

  To open a text file for input: connect a text file to a stream for reading a BufferedReader object, which uses FileReader to open a text file FileReader “connects” BufferedReader to the text file

    FileReader s = new FileReader(“input.txt");

    BufferedReader inStream = new BufferedReader(s);

Or:

    BufferedReader inStream = new BufferedReader(new FileReader(“input.txt"));

             

            

 

 

try {

   FileReader fr=new FileReader("input.txt");

   BufferedReader inputStream = new BufferedReader(fr);

   String line = null;

   while((line=inputStream.readLine())!=null) // Check whether reached the end

    System.out.println(line); // Read a line from the file

     inputStream.close();

  } catch(FileNotFoundException e) {

  System.out.println("File not found.");

  } catch(IOException e) {

  System.out.println("Error reading from file " + fileName);

 }

 

 

StringTokenizer

There are methods to read a line and a character, but not just a single word

  StringTokenizer:

    Token: a block of (useful) text

    Delimiter: is a character used to separate items of data

    E.g., CSV files: comma-delimited 

  Create a StringTokenizer instance you can specify delimiters (the character or characters that separate words)

    the default delimiters are: space, tab, and newline

        StringTokenizer(String str, String delim, boolean returnDelims) //str--The string to be separated      delim--The delimiters     returnDelims--Whether return delimiters as tokens

Read an integer by using BufferedReader

  No methods to read numbers directly Read numbers as Strings and then convert them:

  try{

    String line =inputStream.readLine();

    int value = Integer.parseInt(line);

    } catch(java.lang.NumberFormatException e){

      …

     } catch(IOException e){ …}

Creating Scanner objects

  We can create a Scanner object by invoking several different constructors.

  Scanner(File source)

  Constructs a new Scanner that produces values scanned from the specified file.

  Scanner(InputStream source)         

  Constructs a new Scanner that produces values scanned from the specified input stream.

  Scanner(String source)          

  Constructs a new Scanner that produces values scanned from the specified string. …

  Example (read a line from keyboard):

   Scanner sc = new Scanner (System.in);

Next Methods/hasNext methods

  Example:

  Scanner sc = new Scanner(System.in);

  int i=sc.nextInt();

 

  Scanner sc = new Scanner (System.in);

  System.out.print ("Enter first int: ");

  while (sc.hasNextInt()) {

    int i = sc.nextInt();

    System.out.println("You entered " + i);

    System.out.print ("Enter another int: ");

  }

 

Delimiters in Scanner 

  Default delimiters are: space, tab, new line


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM