2017-03-06 42 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

相关问题