[英]Converting a binary number to decimal from a file with whitespace
我正在尝试将文件中的二进制数字转换为十进制。 我能够获取要转换的数字,但是,在我的文本文件中,如果一行中有多个二进制数,则代码会跳过它。
List<Integer> list = new ArrayList<Integer>();
File file = new File("binary.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
try {
list.add(Integer.parseInt(text,2));
}
catch (Exception ex) {
continue;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这也是我正在使用的文本文件:
00100101
00100110 01000001
01100000
01111011
10010100 00100101
01101011
11000111 00011010
当我运行代码时,我得到:[37,96,123,107]代码跳过有两个二进制数字的行。 我在尝试能够转换整数而不在while循环中不使用reader.readLine()时遇到麻烦。 任何帮助是极大的赞赏!
使用text.split("\\\\s+")
拆分while
循环读取的每一行,并迭代拆分值:
String text = null;
while ((text = reader.readLine()) != null) {
for (String value : text.split("\\s+")) {
try {
list.add(Integer.parseInt(value,2));
}
catch (Exception ex) {
continue; // should throw error: File is corrupt
}
}
}
当一行中有多个值时,应该这样做。
您遍历多个值并分别添加它们。
try {
for (String s : text.split(" ") list.add(Integer.parseInt(s,2));
}
另外,就像Andreas所写的那样,不建议忽略Exception。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.