Read file As String

AndroidStringOptimization

Android Problem Overview


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;
}

Android Solutions


Solution 1 - Android

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;
}

Solution 2 - Android

You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.

e.g.

IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)

For adding the correct library:

> Add the following to your app/build.gradle file: > > dependencies { > compile 'org.apache.directory.studio:org.apache.commons.io:2.4' > } > > - https://stackoverflow.com/a/33820307/1815624</cite>

or for the Maven repo see -> this link

For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi

Solution 3 - Android

Reworked the method set originating from -> the accepted answer

@JaredRummler An answer to your comment:

> https://stackoverflow.com/questions/12910503/read-file-as-string#comment56574366_13357785 > > Won't this add an extra new line at the end of the string?

To prevent having a newline added at the end you can use a Boolean value set during the first loop as you will in the code example Boolean firstLine

public static String convertStreamToString(InputStream is) throws IOException {
   // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    Boolean firstLine = true;
    while ((line = reader.readLine()) != null) {
        if(firstLine){
            sb.append(line);
            firstLine = false;
        } else {
            sb.append("\n").append(line);
        }
    }
    reader.close();
    return sb.toString();
}

public static String getStringFromFile (String filePath) throws IOException {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}

Solution 4 - Android

It's very easy if you use Kotlin:

val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)

From readText() docs:

> Gets the entire content of this file as a String using UTF-8 or > specified charset. This method is not recommended on huge files. It > has an internal limitation of 2 GB file size.

Solution 5 - Android

With files we know the size in advance, so just read it all at once!

String result;
File file = ...;

long length = file.length();
if (length < 1 || length > Integer.MAX_VALUE) {
    result = "";
    Log.w(TAG, "File is empty or huge: " + file);
} else {
    try (FileReader in = new FileReader(file)) {
        char[] content = new char[(int)length];

        int numRead = in.read(content);
        if (numRead != length) {
            Log.e(TAG, "Incomplete read of " + file + ". Read chars " + numRead + " of " + length);
        }
        result = new String(content, 0, numRead);
    }
    catch (Exception ex) {
        Log.e(TAG, "Failure reading " + this.file, ex);
        result = "";
    }
}

Solution 6 - Android

public static String readFileToString(String filePath) {
	InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
	try {
		return IOUtils.toString(in, StandardCharsets.UTF_8);
	} catch (IOException e) {
		logger.error("Failed to read the xml : ", e);
	}
	return null;
}

Solution 7 - Android

this is working for me

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

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;

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPanosView Question on Stackoverflow
Solution 1 - AndroidPanosView Answer on Stackoverflow
Solution 2 - AndroidEugene DudnykView Answer on Stackoverflow
Solution 3 - AndroidCrandellWSView Answer on Stackoverflow
Solution 4 - AndroidvovahostView Answer on Stackoverflow
Solution 5 - AndroidAdam FanelloView Answer on Stackoverflow
Solution 6 - AndroidBhujang BhagasView Answer on Stackoverflow
Solution 7 - AndroidKhanView Answer on Stackoverflow