我正在尝试将文件中的二进制数转换为十进制数。我能够获取要转换的数字,但是,在我的文本文件中,如果一行中有多个二进制数字,代码就会跳过它。
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
}
}
}
关于java - 将带有空格的文件中的二进制数转换为十进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34122086/