我试图将保存到.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)
如果更换'writer.write(总);'和'writer.write(” 0“);'你还在保存奇怪的字符 – Gab
当我改变代码,它是保存”0“ – Kyle
用引号或没有引号 – Gab