下面是我如何计算文本文件中的行数。只是想知道还有什么其他的方法可以做到吗?
while(inputFile.hasNext()) {
a++;
inputFile.nextLine();
}
inputFile.close();
我试图将数据输入到数组中,我不想读取文本文件两次。
如有任何帮助/建议,我们将不胜感激。
谢谢
发布于 2014-10-18 23:38:39
如果您只想将数据添加到数组中,则将新值追加到数组中。如果您正在读取的数据量不是很大,而且您不需要经常这样做,那么这应该是可以的。我使用类似这样的东西,正如在这个答案中给出的:用Java读取纯文本文件
BufferedReader fileReader = new BufferedReader(new FileReader("path/to/file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
如果用数字读取,字符串可以转换为数字,例如整数intValue =Integer.parseInt(文本)
发布于 2014-10-18 23:34:53
如果使用的是java 7或更高版本,则可以使用readAllLines方法将所有行直接读取到列表中。那会很容易
List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
然后,列表的大小将返回文件中的行数。
int noOfLines = lines.size();
发布于 2014-10-19 00:25:30
如果您使用的是Java 8,则可以使用流:
long count = Files.lines(Paths.get(filename)).count();
这将有良好的表现和真正的表现力。
缺点(与Thusitha答案相比)是只有行数。如果还希望在列表中包含行,则可以这样做(仍然使用Java 8流):
// First, read the lines
List<String> lines = Files.lines(Paths.get(filename)).collect(Collectors.toList());
// Then get the line count
long count = lines.size();
https://stackoverflow.com/questions/26448352
复制相似问题