此代码读取记事本文件 这个记事本文件上有数字 10 由于某种原因它返回一个乱码而不是 10 我认为这是 ascii 代码,但我不知道 另外,此代码是根据我的编程老师的代码修改的,因此我不会因此而获得功劳
/**
*Goes in to the file and extracts a number.
* @param fileName
* @return an integer
*/
static int getNumberFromFile(String fileName){
int j = 599;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
String input = sc.nextLine();
j = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return j;
}
throws this wierd exception Exception: java.lang.NumberFormatException: For input string: "10" and this code
/**
* writes data for the ai to adapt its strategy
*@param number is the number to write
* @param fileName is the fileName
*/
public static void writeToFile(String fileName,int number) {
BufferedWriter output = null;
try {
File aFile = new File(fileName);
FileWriter myWriter = new FileWriter(aFile);
output = new BufferedWriter(myWriter);
output.write(number);
output.newLine();
output.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
System.out.println("please Report this bug it doesnt understand");
System.exit(1);
}
}
不要担心一些异常捕获的事情,这些是为了让我看看异常是否被捕获,它只是打印一条(无意义的)消息。和一些关于人工智能的讨论不用担心只需要这段代码工作的东西我可以发布为什么人工智能需要它但我不认为它是相关的
最佳答案
这行代码没有达到您的预期:
output.write(number);
它正在 BufferedWriter
上调用 write
,因此您应该查阅 documentation ...此时您发现您正在调用 this method .
public void write(int c) throws IOException
Writes a single character.
Overrides:
write
in classWriter
Parameters:
c
-int
specifying a character to be written
点击write
链接可获取更多详细信息:
Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored. Subclasses that intend to support efficient single-character output should override this method.
所以,您正在编写 Unicode 字符 U+000A - 或者如果该值实际上是 10,那么就会是这样。我强烈怀疑它不是,因为那只是一个换行字符。
如果您尝试编写数字的十进制表示形式,则应先将其转换为字符串:
output.write(String.valueOf(number));
关于java - 文件解析代码给了我异常而不是数字,文件写入代码给出了乱码而不是数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31729801/