我已阅读之前的帖子并尝试将代码集成到我的项目中。 我正在尝试从 txt 文件中读取整数。 我正在使用这个方法:
static Object[] readFile(String fileName) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
我不知道数据的大小,所以我使用List 在主要调用方法中:
Object [] arr = readFile("C:\\02.txt");
System.out.println(arr.length);
我发现数组大小为 0; 我试图从文件中读取的整数是二进制序列。 (1010101010...) 我认为问题与扫描仪有关,也许他认为这不是整数。
最佳答案
您可以使用BufferReader
代替:
String line = "";
List<Integer> tall = new ArrayList<Integer>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine())!= null) {
tall.add(Integer.parseInt(line, 2));
}
br.close();
}catch(IOException e) {}
关于java - 如何在Java中正确读取文件中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23181757/