2011-10-29 35 views
5

在Java中,是否有一種讀取文件(文本文件)的方式,它只能一次讀取一個字符,而不是字符串字符串。這是爲了一個非常基本的詞法分析器的目的,所以你可以理解爲什麼我想要這樣的方法。謝謝。從文本文件逐個字符地讀入

+0

其實,我不明白;你如何處理輸入與你的閱讀方式不一樣。國際海事組織(IMO)應該使用緩衝閱讀器並按字符處理輸入字符,而不是以這種方式明確閱讀它。 –

回答

3

可以讀取整個文件(如果它沒有太多大),在內存中的字符串,通過字符

+2

也不是一個答案。 – FailedDev

+1

這是一個答案,你認爲它應該包含一個代碼是一個答案! –

5

這裏重複的字符串的字符是用於讀取的示例代碼/在一個時間

寫一個字
public class CopyCharacters { 
    public static void main(String[] args) throws IOException { 

     FileReader inputStream = null; 
     FileWriter outputStream = null; 

     try { 
      inputStream = new FileReader("xanadu.txt"); 
      outputStream = new FileWriter("characteroutput.txt"); 

      int c; 
      while ((c = inputStream.read()) != -1) { 
       outputStream.write(c); 
      } 
     } finally { 
      if (inputStream != null) { 
       inputStream.close(); 
      } 
      if (outputStream != null) { 
       outputStream.close(); 
      } 
     } 
    } 
} 

請注意,此答案已更新爲從Ref鏈接複製示例代碼,但我看到這與以下給出的答案基本相同。

REF: http://download.oracle.com/javase/tutorial/essential/io/charstreams.html

+1

不是一個答案而是一個評論。 – FailedDev

+0

你看過鏈接嗎?它顯示瞭如何逐字讀取文本文件。 – 2011-10-29 20:48:53

+0

把它評論呢? – FailedDev

1

可以使用讀取方法從使用InputStreamReader類,其讀取從所述流中的一個字符並返回-1,當它到達該流

public static void processFile(File file) throws IOException { 
     try (InputStream in = new FileInputStream(file); 
      Reader reader = new InputStreamReader(in)) { 

      int c; 
      while ((c = reader.read()) != -1) { 
       processChar((char) c); // this method will do whatever you want 
      } 
     } 
    } 
0

有的端部幾種可能的解一般來說,你可以使用來自java.io包的任何Reader用於讀取字符,例如:

// Read from file 
BufferedReader reader = new BufferedReader(new FileReader("file.txt")); 
// Read from sting 
BufferedReader reader = new BufferedReader(new StringReader("Some text"));