开发者

Internal Storage android -Device memory

开发者 https://www.devze.com 2023-01-04 14:55 出处:网络
Can some one help me explain how to read and display the data stored in the Internal Storage-pr开发者_JAVA技巧ivate data on the device memory.

Can some one help me explain how to read and display the data stored in the Internal Storage-pr开发者_JAVA技巧ivate 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号