简体   繁体   中英

Internal Storage android -Device memory

Can some one help me explain how to read and display the data stored in the Internal Storage-private data on the device memory.

String input=(inputBox.getText().toString());
String FILENAME = "hello_file"; //this is my file name
FileOutputStream fos;
try {
    fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(input.getBytes()); //input is got from on click button
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    fos1=  openFileInput (FILENAME);
} catch (FileNotFoundException e) {}
outputView.setText(fos1./*I don't know what goes here*/);

openFileInput returns a FileInputStream object. Then, you will have to read the data from it using the read methods it provides.

// missing part...
int len = 0, ch;
StringBuffer string = new StringBuffer();
// read the file char by char
while( (ch = fin.read()) != -1)
    string.append((char)ch);
fos1.close();
outputView.setText(string);

Take a look at FileInputStream for further reference. Keep in mind that this will work fine for text files... if it's a binary file it will dump weird data into your widget.

There are a lot of ways to read in the text, but using a scanner object is one of the easiest ways for me.

String input=(inputBox.getText().toString());
String FILENAME = "hello_file"; //this is my file name
FileOutputStream fos;
try {
    fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(input.getBytes()); //input is got from on click button
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
String result = "";
try {
    fos1=  openFileInput (FILENAME);
    Scanner sc = new Scanner(fos1);
    while(sc.hasNextLine()) {
        result += sc.nextLine(); 
    }
} catch (FileNotFoundException e) {}
outputView.setText(result);

You need to import java.util.Scanner; for this to work. The Scanner object has other methods too like nextInt() if you want to get more specific information out of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM