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; }
You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as a List of String e.g. into an ArrayList, you can use Files. readAllLines() method. This returns a List of String, where each String represents a single line of the file.
The read() method reads in all the data into a single string. This is useful for smaller files where you would like to do text manipulation on the entire file. Then there is readline() , which is a useful way to only read in individual lines, in incremental amounts at a time, and return them as strings.
The readAllLines() method of the Files class allows reading the whole content of the file and stores each line in an array as strings.
Finally, use java 8 stream api collect() and joining() methods to convert List to String. * Java example to convert File To String. List<String> lines = Files. readAllLines(Paths.
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; }
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