1

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

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.