gian848396 gian848396 - 4 months ago 8
Android Question

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;
}

Answer

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()));
}

You can find additional examples and explanations in the Documentation (beta) topic.

Comments