简体   繁体   中英

how can i read specific lines from a textfile in java 8?

So, I need to read a text file line by line, and return them by strings. I can specify from which line to which line do i want to read it.

My class has 3 methods:

public class FilePartReader {

    String filePath;
    Integer fromLine;
    Integer toLine;

    public FilePartReader() { }

    public void setup(String filepath, Integer fromLine, Integer toLine) {
        if (fromLine < 0 || toLine <= fromLine) {
            throw new IllegalArgumentException(
                    "fromline cant be smaller than 0 and toline cant be smaller than fromline");
        }
        this.filePath = filepath;
        this.fromLine = fromLine;
        this.toLine = toLine;
    }

    public String read() throws IOException {
        String data;
        data = new String(Files.readAllBytes(Paths.get(filePath)));
        return data;
    }

    public String readLines() {
        return "todo";
    }
}

read() method should open the filepath, and return the contents as a string. readLines() should read the file with read() and give back every line from it's content between fromLine and toLine (both of them are included), and returns these lines as a String. Now, im not sure if read() is implemented correctly, since if i understand right that will return the whole content as one big String, maybe there is a better solution for this? Also, how can i make the fromLine/toLine work? thanks in advance

You can use Files.lines which returns a Stream<String> with all lines and apply skip and limit to the result stream:

Stream<String> stream = Files.lines(Paths.get(fileName))
                             .skip(fromLine)
                             .limit(toLine - fromLine);

This will give you a Stream of lines starting from fromLine and ending at toLine . After that you can either convert it to a data structure (a list for example) or do whatever needs to be done.

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