1. 程式人生 > >3.7.3 檔案輸入與輸出

3.7.3 檔案輸入與輸出

    想要對檔案進行讀取,就需要一個File物件構造一個Scanner物件,如下所示:         Scanner in = new Scanner(Paths.get("myfile.txt), "UTF-8");       如果檔名中包含反斜槓符號,就要記住在每個反斜槓之前再加一個額外的反斜槓:"c:\\mydirectory\\myfile.txt"       import java.io.IOException;     import java.lang.Exception;     import java.nio.file.Paths;         public static void main(String[] args) throws IOException {             Scanner in = new Scanner(Paths.get("C:\\Users\\Avention\\myfile.txt"),"UTF-8");  //以後都使用絕對路徑吧                          try{                   while (true){                   String s = in.nextLine();                   System.out.println(s);                   }             }             catch (Exception e){                   e.printStackTrace();                                }       }   ?Mark 滿意 Josn java.util.NoSuchElementException: No line found       at java.util.Scanner.nextLine(Unknown Source)       at myjavapp.Hello.main(Hello.java:22)         註釋:上述程式碼中指定了"UTF-8"字元編碼,這對於網際網路上的檔案很常見(不過並不是普遍適用)。讀取一個文字檔案時,要知道它的字元編碼。如果省略字元編碼,則會適用執行這個Java程式的機器的“預設編碼”。這不是一個好主意,如果在不同的機器上執行這個程式,可能會有不同的表現。            現在,就可以利用前面介紹的任何一個Scanner方法對檔案進行讀取。     要想寫入檔案,就需要構造一個 PrintWriter 物件。在構造器中,只需要提供檔名:         PrintWriter out = new PrintWriter("myfile.txt","UTF-8");       如果檔案不存在,建立該檔案。可以像輸出到System.out一樣使用print、println、printf命令         public static void main(String[] args) throws IOException {             PrintWriter out = new PrintWriter("C:\\Users\\Avention\\myfile1.txt","UTF-8");             for(int n=1;n<=10;n++){                   out.println(n+" Mark");             }             out.close();  //檔案寫完要關閉,切記。       } }         訪問檔案與使用System.in 和 System.out一樣容易,如果用一個不存在的檔案構造一個Scanner,或者不能被建立的檔案明後才能構造一個PrintWriter,那麼就會發生異常。Java編譯器認為這些異常比“被零除”異常更嚴重。         註釋:當採用命令列方式啟動一個程式時,可以利用Shell的重定向語法將任意檔案關聯到System.in和System.out;         java MyProg < myfile.txt > output.txt         這樣就不用擔心處理IOException異常了。   java.util.Scanner     Scanner(File f) 構造一個從給定檔案讀取資料的Scanner。     Scanner(String data) 構造一個從給定字串讀取資料的Scanner。   java.io.PrintWriter     PrintWriter(String filename) 構造一個將資料寫入檔案的PrintWriter。檔名由引數指定。   java.nio.file.Paths     static Path get(String pathname)  根據給定的路徑名構造一個Path。