![](/img/trans.png)
[英]NumberFormatException when converting Integer String in Java
[英]Reading / Writing number in Java — Then NumberFormatException when converting
我有一個寫為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", "")));
它將從返回的數字中刪除所有空格字符(由regex元字符\\s
)。
您要添加換行符:
while ((line = reader.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
因此,您嘗試解析的不是數字122\\n
。 不要添加換行符。
實際上,您正在逐行閱讀然后添加換行符,僅將原始字節寫入String
難道不是嗎?
進一步的評論:
finally
使用。 Data(Out|In)PutStream
並將數字直接寫為二進制。 null
然后重新分配它們的習慣。 例如,在此代碼中,如果您未能創建writer
,則您的finally
會收到NullPointerException
。 static
方法,例如以靜態工廠模式。 Path
API Files
實用程序類 您的實用程序方法在您的String中添加了行分隔符,因此失敗
logger.info("String converted to number: " + Integer.parseInt(numberString));
你可以做這樣的事情,
String numberString = Util.getContents(new File("D:/TEST.TXT"));
numberString = (numberString != null) ? numberString.trim() : "0";
// now this is a safe call
logger.info("String converted to number: " + Integer.parseInt(numberString));
如果我正確地假設您正在嘗試創建它,以便記錄器在讀取文件時轉到新行,如果是這樣,那么您將其放置在哪里:
logger.info("String: " + numberString);
在您的numberString后面加上+"\\n"
,它應該添加新行。 但是當然,考慮到Logger默認情況下每次logger.info(anyString)
調用都寫入新行,這是非常不必要的。 無論哪種方式,當您將String解析為Int時,String都只能包含整數字符以及-
字符。 line.separator
字符串通常為“ \\ n”,並且顯然不是數字,並返回錯誤。
您可以執行numberString.replaceAll("[^\\\\d.]", "");
確保沒有非數字字符附加到您的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.