2017-02-17 2 views
-1

私は出力のPrintStreamのみ入力ファイルの最後の行をプリントアウト

INPUT.TXTと、入力ファイルの内容があった場合にJavaプログラムを使用して、コマンドラインからこのプログラムを起動した場合、私はこのコード

public class program { 
    public static void main(String[] args) { 
     try { 
      String filePath = (args[0]); 
      String strLine; 

      BufferedReader br = new BufferedReader(new FileReader(filePath)); 

      //Read File Line By Line and Print the content on the console 
      while ((strLine = br.readLine()) != null) { 
      //System.out.println (strLine); 
      PrintStream out = new PrintStream(new FileOutputStream(//printing output to user specified text file (command line argument: outputfile) 
        args[1]+".txt")); 
       out.print(strLine); 
      } 
      //close the streams 
      br.close(); 
      } 
      catch(IOException e){ 
      System.err.println("An IOException was caught :"+e.getMessage()); 
      } 

    } 
} 

を持っていますこの出力ファイルは、これを印刷し

ハロー ハイテク さようなら: さようなら

出力の最後の行だけを出力しています。

かの代わりに:

PrintStream out = new PrintStream(new FileOutputStream(//printing output to user specified text file (command line argument: outputfile) 
       args[1]+".txt")); 
      out.print(strLine); 

私はそれが正しくコンソールへの入力ファイルから各行を印刷し、whileループ内

System.out.println (strLine); 

を持っていました。

なぜ別のファイルに印刷しようとすると、最後の行だけが印刷されるのですか?

答えて

1

各ループに新しいPrintStreamを作成しないでください。代わりにwhileループの前にPrintStreamを作成します。

PrintStream out = new PrintStream(...); 
while ((strLine = br.readLine()) != null) { 
    out.print(strLine); 
}    
+1

ところで、もしあなたが 'out.println()'を使って改行を保持したいならば、 – coolioasjulio

0

あなたがループ内の同じファイルに上書きされますので。ループの外側にないPrintStreamをループ外に作成し、すべての行を書き込む必要があります。

関連する問題