gpt4 book ai didi

java - 在Java中读/写数字——转换时出现NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 18:30:18 25 4
gpt4 key购买 nike

我有一个以 UTF-8 格式写入的数字,然后将其读回(稍后阶段)。然后我将其转换为数字,因为我使用该数字进行算术。我收到 NumberFormatException 但看不到原因。我完全以 UTF-8 进行操作,两种方式都有问题吗?

所以,第一个输出很好,我看到了我的号码(作为字符串)。第二个输出失败并出现 NumberFormatException。

这是我用于写入和读取文件的代码:

static public void putContents(File aFile, String content, boolean append) {

// init
Writer writer = null;

// make sure file exists
if (!aFile.exists()) {
Util.createFile(aFile.getAbsolutePath());
}

// write content
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(aFile), "UTF-8"));
writer.write(content);
writer.close();
} catch (IOException e) {
logger.error("Error writing content to file: " + aFile);
} finally {
try {
// Close the writer regardless of what happens
writer.close();
} catch (Exception e) {
logger.error("Error while closing file: " + aFile.getAbsolutePath());
}
}

}

static public void createFile(String filename) {

// protection against accidental overwrite
if (new File(filename).exists()) {
logger.warn("File '" + filename + "' already exists. Nothing done.");
return;
}

// create file with directory structure
File targetFile = new File(filename);
File parent = targetFile.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new IllegalStateException("Couldn't create dir: " + parent);
}

try {
targetFile.createNewFile();
} catch (IOException e){
logger.error("Error while creating empty file '" + filename + "': " + e.getMessage());
}

}

static public String getContents(File aFile) {

StringBuilder contents = new StringBuilder();

try {
// extract all text from this file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(aFile), "UTF-8"));
try {

String line = null; //not declared within while loop
while ((line = reader.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
reader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}

return contents.toString();
}

这里是我如何生成异常:

public static void main(String[] args) {

putContents(new File("D:/TEST.TXT"), "122", false);
String numberString = Util.getContents(new File("D:/TEST.TXT"));

logger.info("String: " + numberString);
logger.info("String converted to number: " + Integer.parseInt(numberString));

}

此处输出:

16:28:05,109 INFO  [main] [Util] String: 122
Exception in thread "main" java.lang.NumberFormatException: For input string: "122"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at at.tuwien.mucke.util.Util.main(Util.java:154)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Process finished with exit code 1

最佳答案

方法 getContents 在返回值中添加新行。这导致该方法返回 122\r\n

contents.append(System.getProperty("line.separator"));

如果你想删除新行,可以使用:

System.out.println("String converted to number: " + Integer.parseInt(numberString.replaceAll("\r\n", "")));

或者你可以使用

System.out.println("String converted to number: " + Integer.parseInt(numberString.replaceAll("\\s", "")));

这将从返回的数字中删除所有空白字符(由正则表达式元字符 \s 表示)。

关于java - 在Java中读/写数字——转换时出现NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24512968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com