Read entire File to string - Android java.io

Android examples for java.io:Text File

Description

Read entire File to string

Demo Code

import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{

    public static String getStringFromFile(File file) {
        BufferedReader reader;// w ww  . j  a  v a 2s.c om
        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            if (reader != null) {
                StringBuilder builder = new StringBuilder();
                try {
                    for (String line = null; (line = reader.readLine()) != null;) {
                        builder.append(line).append("\n");
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Can't read stream", e);
                }
                reader.close();
                return builder.toString();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e(TAG, "IOException", e);
        }
        return null;
    }

}

Related Tutorials