![](/img/trans.png)
[英]How to get the number of lines from a text file in java ignoring blank lines?
[英]How to get the number of lines from a text file in java?
我是Java的新手。 我想在测试文件中找到行数,以便可以将其用于数组大小。 我最初的想法是创建一个循环并更新一个int变量。 像这样:
Scanner file = new Scanner(new File("data.text"));
int n = 0;
while(file.hasNextLine()) {
file.nextLine();
n++;
}
int[] array = new int[n];
这对我不起作用,因为扫描仪文件位于文本文件的末尾。 除非关闭原始文件并创建一个新的扫描仪对象,否则我将无法读取该文本文件。 有没有更好的方法来执行此操作?
如果您使用的是1.7+,则可以像这样直接存储到数组。
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// more code
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
根据实际需要执行的操作,您可能希望将整个文件保留在内存中。
List<String> lines = Files.readAllLines(Paths.get("data.text"));
// Here you can easily obtain the list size
lines.size()
如果您不需要实际的线条或不是全部线条,可以执行以下操作
long lineCount = Files.lines(Paths.get("data.text")).count();
由于它是Java 8 Stream,因此您可以对行进行过滤,解析或执行任何所需的操作。
您可以使用BufferedReader
和FileReader
:
FileReader in = new FileReader("data.txt");
BufferedReader br = new BufferedReader(in);// use this only if you have large files, meaning that each line is very long.
int n = 0;
while (br.readLine() != null) {
n++;
}
System.out.println(n);
in.close();
int[] array = new int[n];
另外,您可以使用ArrayList
代替数组,但这取决于您要如何使用行数。
如果文件不是很大,则可以执行以下操作:
FileReader in = new FileReader("data.txt");
int n = 0;
while ((in.readLine() != null)) {
n++;
}
System.out.println(n);
in.close();
int[] array = new int[n];
好的。 这是您问题的简单答案。 您想使用相同的Scanner对象从头开始再次读取文件而不关闭它。
这样做是不可能的。 。
原因:它支持各种输入类型,它们在传递结果后不存储结果,因此不支持重置。
因此,理想的解决方案是创建一个新的Scanner Object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.