我一直找不到原因。我在这段代码中遇到的唯一问题是,当FileWriter试图将新值放入文本文件时,它会放置一个?我不知道为什么,甚至不知道这意味着什么。以下是代码:
if (secMessage[1].equalsIgnoreCase("add")) {
if (secMessage.length==2) {
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) + 1;
write.write(comb);
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}下面是readFile方法:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}此外,secMessage数组是一个字符串数组,其中包含一个IRC消息的单词被分割成单独的单词,这样程序就可以逐个逐字地对命令做出反应。
发布于 2014-08-10 06:36:33
你给Writer.write(int)打电话。它只编写一个UTF-16代码指向文件,只占下16位.如果您的平台默认编码无法表示您要编写的代码点,它将写入“?”作为替代角色。
我怀疑您实际上想要写出数字的文本表示,在这种情况下,您应该使用:
write.write(String.valueOf(comb));换句话说,将值转换为字符串,然后将其写出。因此,如果comb是123,您将得到三个字符('1','2','3')写入文件。
但就我个人而言,我会避免使用FileWriter --我更喜欢使用OutputStreamWriter包装FileOutputStream,这样您就可以控制编码。或者在Java 7中,您可以使用Files.newBufferedWriter进行更简单的操作。
发布于 2014-08-10 06:36:23
write.write(new Integer(comb).toString());可以将int转换为字符串。否则,您将需要int作为一个字符。这将只适用于一小部分数字,0-9,所以不建议。
https://stackoverflow.com/questions/25226162
复制相似问题