简体   繁体   中英

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:

Galatasaray beat Juventus 1-0 last night.

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.

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.

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 . Call readLine() on it until it returns null , then getLineNumber() to know the last line number, and you're done !

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.

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 ?

Using 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...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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