read string From File - Android java.io

Android examples for java.io:Text File

Description

read string From File

Demo Code

import android.content.Context;
import android.location.Location;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main{

    public static String readFromFile(Context context, String fileName) {
        InputStream is = null;//from   w w  w. jav a 2 s  . c o m
        StringBuilder sb = new StringBuilder();

        //      String temp = null;
        File file;
        if (fileName == null || fileName.equals("")) {
            return null;
        }
        try {
            file = context.getFileStreamPath(fileName);
            is = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            int c;
            char[] charStr = new char[1024];
            while ((c = isr.read(charStr)) != -1) {
                sb.append(charStr, 0, c);
            }

            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sb.toString();

    }

}

Related Tutorials