gian848396
gian848396

Reputation: 478

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.

private String GetPhoneAddress() {
    File directory = Environment.getExternalStorageDirectory();
    File myFile = new File(directory, "mythoughtlog.txt");
    //File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
    if (!myFile.exists()){
        String line = "Need to add smth";
        return line;
    }
    String line = null;
    //Read text from file
    //StringBuilder text = new StringBuilder();
    try {
        BufferedReader br = new BufferedReader(new FileReader(myFile));
        line = br.readLine();
    }
    catch (IOException e) {
        //You'll need to add proper error handling here
    }
    return line;
}

Upvotes: 2

Views: 75

Answers (2)

Mureinik
Mureinik

Reputation: 311163

You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):

try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
    String line = br.readLine();
    if (line == null) {
        return null;
    }
    StringBuilder retVal = new StringBuilder(line);
    line = br.readLine();
    while (line != null) {
        retVal.append(System.lineSeparator()).append(line);
        line = br.readLine();
    }
    return retVal.toString();
}

if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:

try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
    return br.lines().collect(Collectors.joining(System.lineSeparator()));
}

Upvotes: 2

user207421
user207421

Reputation: 310875

A considerably less verbose solution:

try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
    StringBuilder retVal = new StringBuilder();
    while ((line = br.readLine()) != null) {
        retVal.append(line).append(System.lineSeparator());
    }
    return retVal.toString();
}

Upvotes: 2

Related Questions