2017-03-06 44 views
1

我試圖將保存到.txt文件的數字值轉換爲int,然後添加此int和另一個在程序中定義的值。本節似乎沒有問題,但是當我嘗試將此新值保存回原始文件.txt時,出現了一個奇怪的符號。寫入.txt文件時會出現奇怪的「框」符號

/* 
* @param args the command line arguments 
*/ 
public class TestForAqTablet1 { 

    public static void main(String[] args) { 
     int itemval=0; 
     String itemcount= "3"; 
     try{ 
      BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\kyleg\\Documents\\AQ App Storage\\stock\\1~ k\\od.txt")); 
      String line; 
      System.out.println("reading file"); 
      while((line = in.readLine()) != null){ 
       itemval = Integer.parseInt(line); 
      } 
      in.close(); 
     } 
     catch (IOException ex) { 
      Logger.getLogger(TestForAqTablet1.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     //math 
     System.out.println("previous number "+itemval); 
     System.out.println("count "+itemcount); 
     int total = itemval + Integer.parseInt(itemcount); 
     System.out.println("Total: "+total); 

     //write 
     try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\kyleg\\Documents\\AQ App Storage\\stock\\1~ k\\od.txt"), StandardCharsets.UTF_8))) { 
      writer.write(total); 
     catch (IOException ex) { 
       // handle me 
      } 
     } 
    } 
} 

.txt文件它是從閱讀中只包含數0

我的目標是每次程序運行時增加一個指定的編號(itemcount)。

這是我不斷收到錯誤:

run: 
reading file 
Exception in thread "main" java.lang.NumberFormatException: For input string: "" 
     at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
     at java.lang.Integer.parseInt(Integer.java:569) 
     at java.lang.Integer.parseInt(Integer.java:615) 
     at test.pkgfor.aq.tablet.pkg1.TestForAqTablet1.main(TestForAqTablet1.java:37) 
C:\Users\kyleg\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 
BUILD FAILED (total time: 0 seconds) 
+0

如果更換'writer.write(總);'和'writer.write(」 0「);'你還在保存奇怪的字符 – Gab

+0

當我改變代碼,它是保存」0「 – Kyle

+0

用引號或沒有引號 – Gab

回答

2

你是不是寫一個文本文件。您正在編寫一個值爲char的位。從the documentation of Writer.write(int)

寫入一個字符。要寫入的字符包含在給定整數值的16個低位中; 16位高位被忽略。

如果你想使用一個作家,你必須將數據轉換爲字符串寫入文本:

writer.write(String.valueOf(total)); 
+0

你的代碼已經工作了,謝謝 – Kyle

相關問題