![](/img/trans.png)
[英]why is the “data” parameter in my gridOptions (ng-grid) always empty?
[英]Why is my text file always empty?
我創建了一個游戲,將您的高分保存在名為highscores.txt的文本文件中。 當我打開游戲時,顯示正確的高分。 但是,當我打開文本文件時,它始終為空。 為什么是這樣? 這是我用於編寫和讀取文本文件的代碼。
FileInputStream fin = new FileInputStream("highscores.txt");
DataInputStream din = new DataInputStream(fin);
highScore = din.readInt();
highSScore.setText("High Score: " + highScore);
din.close();
FileOutputStream fos = new FileOutputStream("highscores.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(highScore);
dos.close();
DataOutputStream.writeInt
不會將整數寫為文本; 它寫入由4個字節組成的“原始”或“二進制”整數。 如果嘗試將它們解釋為文本(例如,通過在文本編輯器中查看它們),則會收到垃圾,因為它們不是文本。
例如,如果您的分數是100, writeInt
將按該順序寫入0字節,0字節,0字節和100字節。 0是無效字符(當解釋為文本時),而100恰好是字母“ d”。
如果要編寫文本文件,則可以使用Scanner
進行解析(讀取),並使用PrintWriter
進行書寫-如下所示:
// for reading
FileReader fin = new FileReader("highscores.txt");
Scanner sc = new Scanner(fin);
highScore = din.nextInt();
highScore.setText("High Score: " + highScore);
sc.close();
// for writing
FileWriter fos = new FileWriter("highscores.txt");
PrintWriter pw = new PrintWriter(fos);
pw.println(highScore);
pw.close();
(當然,還有許多其他方法可以執行此操作)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.