Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is most appropriate way to read all data from a text file in one go?

I have a text file and I want to read the entire contents of it into a String variable. The file is being opened as an InputStream as I am using Android's assetManager.open() method.

What is the best practise way to read the entire contents into a String? I am currently wrapping the InputStream with an InputStreamReader and then a BufferedReader and using a while loop I read in the text line by line with the readLine() method.

Is there a better way of reading in this text considering I there is no requirement to read it in line by line, I'd like to get it all in one go if possible

like image 335
sonicboom Avatar asked Dec 31 '12 13:12

sonicboom


People also ask

Which method is used to read data from a text file?

To read from a text file Use the ReadAllText method of the My. Computer. FileSystem object to read the contents of a text file into a string, supplying the path. The following example reads the contents of test.

Which method is used to read the whole file at once?

The read() method returns the entire contents of the file as a single string (or just some characters if you provide a number as an input parameter. The readlines method returns the entire contents of the entire file as a list of strings, where each item in the list is one line of the file.

What is the safest and most Pythonic way to open filename TXT for reading?

Reading text files in Python is relatively easy to compare with most of the other programming languages. Usually, we just use the “open()” function with reading or writing mode and then start to loop the text files line by line. This is already the best practice and it cannot be any easier ways.


2 Answers

This is what Java 7 Files.readAllLines method does - I would expect it to be a very good way of doing it (it uses a try-with-resources syntax which is easily transposable to work on android):

public static List<String> readAllLines(Path path, Charset cs) throws IOException {
    try (BufferedReader reader = newBufferedReader(path, cs)) {
        List<String> result = new ArrayList<String>();
        for (;;) {
            String line = reader.readLine();
            if (line == null)
                break;
            result.add(line);
        }
        return result;
    }
}

In your case, you could append the strings to a StringBuilder instead of adding them to a list.

like image 140
assylias Avatar answered Sep 21 '22 01:09

assylias


One normally should not reinvent the wheel, so use the apache commons library, if the overhead is bearable on Android. Use org.apache.commons.io.IOUtils.toString.

InputStream in = new FileInputStream(new File("a.txt"));
String s = IOUtils.toString(in, "UTF-8");
like image 36
Joop Eggen Avatar answered Sep 18 '22 01:09

Joop Eggen