2016-04-09 18 views
1

私が何をしたとしても、ファイルの新しい行に新しいデータを書き込まなかった。 どうすれば修正できますか?与え)(たとえば、メアリーのスコアについてはファイルの新しい行にデータを書き込むことができない

は100で、スミスのスコアは150ですが、txtファイルで、それは私が新しい行にsmith 150をしたい

mary 100smith 150 

public class HighScores { 
public HighScores(){ 

    String txt = ""; 
    Scanner sc = null; 
    PrintWriter pw = null; 
    File Checker = null; 
    try{ 
     Checker = new File("highScores.txt"); 
     if(!Checker.exists()){ 
      Checker.createNewFile(); 
     } 


sc = new Scanner(new File("highScores.txt")); 
     while(sc.hasNextLine()){ 
      txt = txt.concat(sc.nextLine()+"\n"); 
     } 

     String score=String.valueOf(Game3.score); 
     String name = NewPlayer.name; 

     txt = txt.concat(name + " "+ score +"\n"); 
     pw = new PrintWriter(Checker);// writing the checker 
     pw.write(txt +"\r\n"); 

pw.printlnです同じ問題もあります。

}catch(FileNotFoundException fnfe){ 

     fnfe.printStackTrace(); 
    }catch(IOException ioe){ 
     ioe.printStackTrace(); 
    }finally{ 
     sc.close(); 
     pw.close(); 
    } 

} 

} 
+1

を使用してください。 PrintWriterを開き、println()を使用してテキストを書き込んだ後にEOLを書き込むか、print()を実行してEOLが続かないテキストを書き出します。 Javaの命名規則を尊重します。変数は小文字で始まります。 –

+0

私はprintlnを使用しましたが、もう一度、2番目のデータは新しい行にありません – hekinci

+0

すべてのコードを変更してこの新しいコメントを1分以内に書き込む方法はありません。私のコメントをもう一度読んでください。 –

答えて

0

コードは厄介ですが、実際にあなたが期待しているものを実行する必要があります。

おそらく、結果のファイルをWindowsメモ帳アプリケーションで表示している可能性があります。他のほとんどのWindowsアプリケーションと同様に、改行文字として"\r\n"が期待されています。

+0

いいえJCreatorで結果ファイルを表示しています。 – hekinci

+0

これは依然として原因になります=) 'txt'を' System.out'に出力して、改行が実際に書き込まれているかどうかを調べてください。行区切り記号を '\ r \ n'に変更してみてください。 – ThatDamnRusski

0

は\ n`or `\ rを\ N '` CONCAT()とハードコードを使用しないでください次のコード

public class HighScores { 
public HighScores() { 
    String txt = ""; 
    Scanner sc = null; 
    PrintWriter pw = null; 
    File Checker = null; 
    try { 
     Checker = new File("highScores.txt"); 
     if (!Checker.exists()) { 
      Checker.createNewFile(); 
     } 

     sc = new Scanner(new File("highScores.txt")); 
     while (sc.hasNextLine()) { 
      txt = txt.concat(sc.nextLine() + "\n"); 
     } 

     String score = String.valueOf(Game3.score); 
     String name = NewPlayer.name; 

     txt = txt + name + " " + score; 
     pw = new PrintWriter(Checker);// writing the checker 

     pw.println(txt); 
    } catch (FileNotFoundException fnfe) { 

     fnfe.printStackTrace(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } finally { 
     sc.close(); 
     pw.close(); 
    } 
} 

}

+0

'exists()/ createNewFile()'の部分はいつものように無意味です。単なるコードはここでの答えではありません。説明する必要があります、 – EJP

関連する問題