2011-04-16 23 views

回答

2

閱讀是這樣的,寫的是使用的BufferedWriter的write方法

File file = new File("test.txt"); 
BufferedReader reader = null; 

try { 
    reader = new BufferedReader(new FileReader(file)); 
    int i; 

    // repeat until EOF 
    while ((i = (char)reader.read()) != -1) { 
     char c = (char)i; 
     // do with c whatever you want 
    } 
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } finally { 
    try { 
     if (reader != null) { 
     reader.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

[閱讀](http://download.oracle.com/javase/6/docs/api/java/io/Reader.html#read%28%29)返回一個'int';值「-1」表示EOF。 – McDowell 2011-04-16 16:57:56

+0

對不起,忘記了,修正了 – Troydm 2011-04-17 08:39:48

+0

代碼需要'int i; while((i = r.read())!= -1){char c =(char)i;' – McDowell 2011-04-17 10:15:54

相關問題