Read file As String
android, optimization, string
Solution
The code finally used is the following from:
http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
Problem
I need to load an xml file as String in android so I can load it to TBXML xml parser library and parse it. The implementation I have now to read the file as String takes around 2seconds even for a very small xml file of some KBs. Is there any known fast method that can read a file as string in Java/Android? This is the code I have now: ``` public static String readFileAsString(String filePath) { String result = ""; File file = new File(filePath); if ( file.exists() ) { //byte[] buffer = new byte[(int) new File(filePath).length()]; FileInputStream fis = null; try { //f = new BufferedInputStream(new FileInputStream(filePath)); //f.read(buffer); fis = new FileInputStream(file); char current; while (fis.available() > 0) { current = (char) fis.read(); result = result + String.valueOf(current); } } catch (Exception e) { Log.d("TourGuide", e.toString()); } finally { if (fis != null) try { fis.close(); } catch (IOException ignored) { } } //result = new String(buffer); } return result; } ```