f1tz f1tz - 4 months ago 45
Android Question

Using InputStream to read file from internal storage

I've searched for a couple days, and all I find is using bufferedReader to read from a file on internal storage. Is it not possible to use InputStream to read from a file on internal storage?

private void dailyInput()
{
InputStream in;
in = this.getAsset().open("file.txt");
Scanner input = new Scanner(new InputStreamReader(in));
in.close();
}


I use this now with
input.next(
) to search my file for the data that I need. It all works fine, but I would like to save new files to internal storage and read from them without changing everything to bufferedReader. Is this possible or do I need to bite the bullet and change everything? FYI I don't need to write, only read.

Answer

To write a file.

String FILENAME = "file.txt";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

to read

void OpenFileDialog(String file) {

    //Read file in Internal Storage
    FileInputStream fis;
    String content = "";
    try {
        fis = openFileInput(file);
        byte[] input = new byte[fis.available()];
        while (fis.read(input) != -1) {
        }
        content += new String(input);
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

content will Contain your File Data.