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
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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With