Reputation: 5028
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
Upvotes: 5
Views: 2958
Reputation: 109603
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");
Upvotes: 2
Reputation: 26733
Scanner scanner = new Scanner(file, encoding);
scanner.useDelimiter("\\A");
if (!scanner.hasNext()) { // corner case -- file is empty
return "";
}
String result = scanner.next();
scanner.close();
Upvotes: 0
Reputation: 2555
This is another possible way of doing it.
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
char[] cbuf = new char[500];
br.read(cbuf);
String fileContents = new String(cbuf);
Upvotes: 0
Reputation: 29
You can also use Scanner class
Scanner scan = new Scanner(file);
String content = scan.next();
Upvotes: -1
Reputation: 328785
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.
Upvotes: 5