简体   繁体   English

从文件中读取不可打印字符

[英]Read non-printable character from a file

I'm trying to read a character as an integer from a file and I receive an exception of NumberFormatException:我正在尝试从文件中将字符作为整数读取,但收到 NumberFormatException 异常:

Java.lang.NumberFormatException: For input string: "4 " java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458) at java.lang.Integer.valueOf(Integer.java:554) at Main.main(Main.java:9)

I'm pretty sure it's from the file, as it can be reproduced only when I copy the text to the file, when typed manually, it parses properly.我很确定它来自文件,因为只有当我将文本复制到文件时才能复制它,当手动输入时,它会正确解析。 My question is: how can I avoid this exception and make that "4" to be parsed to the variable?我的问题是:我怎样才能避免这个异常并使“4”被解析为变量? The line where I parse it is: int m = Integer.valueOf(inputFile.readLine());我解析它的行是: int m = Integer.valueOf(inputFile.readLine());

It seems that there are some special characters in your input, to avoid this problem you can use :您的输入中似乎有一些特殊字符,为避免此问题,您可以使用:

int m = Integer.valueOf(inputFile.readLine().replaceAll("[^\\d]+", ""));

Which mean replace any non digit with empty这意味着用空替换任何非数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM