2012-12-18 38 views
0

以下程序應打印String「矮矮胖胖的人坐在牆上,\ n矮矮胖胖的人摔倒了。」到一個文件並將其輸入。使用FileInputStream進行文件輸入無法正常工作

package io; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.PrintStream; 

public class ByteIO { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     String output = "Humpty Dumpty sat on a wall,\n Humpty Dumpty had a great fall."; 
     System.out.println("Output String : " + output); 
     try(PrintStream out = new PrintStream("F:\\Test.txt")) { 
      out.println(output); 
     } catch(FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

     String input = ""; 
     try(FileInputStream in = new FileInputStream("F:\\Test.txt")) { 
      while(in.read() != -1) 
       input += (char)in.read(); 
     } catch(FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch(IOException e) { 
      e.printStackTrace(); 
     } 
     System.out.println("Input String : " + input); 
    } 
} 

但是,我從FileInputStream得到了String是 「upyDmt一個nawl,upyDmt一個RA人?」!另外,當我打開文件「Test.txt」時,我發現輸出String已經變成「矮胖矮胖坐在牆上,矮矮胖胖的人倒下了。」在一行中。 \n去哪了?

+1

\ n在那裏,但也許你的編輯器不會顯示它。關於你的輸入:你的循環被打破,因爲它只提供每個第二個字符。 – Ingo

+0

您應該在寫入和讀取之間關閉文件。 –

+0

@JavaNewbie總是接受答案,當你得到你的解決方案。 – Ravi

回答

0

這是正確解決我的問題:

int i = 0; 
char c; 
    do { 
     c = (char)i; 
     input += c; 
     i = in.read(); 
    } while(i != -1); 

在前面的額外空間是通過使用去除.trim()方法。

4

要調用in.read()兩次:

while(in.read() != -1) 
    input += (char)in.read(); 

這讀取兩個字符每次迭代,而不是一個,所以你每次都有效地丟棄一個字符。

嘗試存儲在while條件的字符,然後就補充說,性格input

編輯:基於JavaNewbie_M107的評論

int i;  
while((i = in.read()) != -1) 
    input += (char)i; 
+0

你的代碼存在的問題是'char' c永遠不會返回-1,相反,它會一直返回零,從而設置一個無限循環。 –

+0

@ JavaNewbie_M107你是對的,我早先錯過了。我會做一個編輯。 –

1

對於第二部分的Windows(和許多應用程序像記事本)不會將\ n識別爲新行。在Windows中,\ r \ n標誌着一條新線。嘗試打開更嚴重的編輯程序(寫字板應該足夠了),你會看到它正確的格式。

+0

+1你說得對。 –

0

正如亨特說,你需要更改您的代碼此

char c; 
while((c=in.read()) != -1) 
input += c;