简体   繁体   English

返回.txt文件中的行数

[英]Returning the number of lines in a .txt file

This is my debut question here, so I will try to be as clear as I can. 这是我在这里的首次发言,因此,我将尽量保持清楚。

I have a sentences.txt file like this: 我有一个这样的句子.txt文件:

Galatasaray beat Juventus 1-0 last night. 昨晚加拉塔萨雷1-0击败尤文图斯。

I'm going to go wherever you never can find me. 我要去你永远找不到我的地方。

Papaya is such a delicious thing to eat! 木瓜真好吃!

Damn lecturer never gives more than 70. 该死的讲师的付出从未超过70。

What's in your mind? 你在想什么?

As obvious there are 5 sentences, and my objective is to write a listSize method that returns the number of sentences listed here. 显然有5个句子,我的目标是编写一个listSize方法,该方法返回此处列出的句子数。

public int listSize()
{
// the code is supposed to be here.

return sentence_total;}

All help is appreciated. 感谢所有帮助。

To read a file and count its lines, use a java.io.LineNumberReader , plugged on top of a FileReader . 要读取文件并计算其行数,请使用插入在FileReader顶部的java.io.LineNumberReader Call readLine() on it until it returns null , then getLineNumber() to know the last line number, and you're done ! 在其上调用readLine() ,直到它返回null ,然后再调用getLineNumber()知道最后一个行号,您就完成了!

Alternatively (Java 7+), you can use the NIO2 Files class to fully read the file at once into a List<String> , then return the size of that list. 或者(Java 7+),您可以使用NIO2 Files类将文件一次完全读入List<String> ,然后返回该列表的大小。

BTW, I don't understand why your method takes that int as a parameter, it it's supposed to be the value to compute and return ? 顺便说一句,我不明白为什么您的方法将int作为参数,它应该是要计算并返回的值?

Using LineNumberReader : 使用LineNumberReader

LineNumberReader  reader = new LineNumberReader(new FileReader(new File("sentences.txt")));
reader.skip(Long.MAX_VALUE);
System.out.println(reader.getLineNumber() + 1); // +1 because line index starts at 0
reader.close();

use the following code to get number of lines in that file.. 使用以下代码获取该文件中的行数。

    try {
        File file = new File("filePath");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        int totalLines = 0;
        while((line = reader.readLine()) != null) {
            totalLines++;
        }
        reader.close();
        System.out.println(totalLines);
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

You could do: 您可以这样做:

Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.readAllLlines(file).size();

If you want to limit them or process them lazily: 如果要限制它们或延迟处理它们:

Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.llines(file).limit(maxLines).collect(Collectors.counting...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM