内部存储android-设备内存

时间:2010-06-25 16:16:02

标签: java android

有人可以帮我解释如何读取和显示存储在设备存储器上的内部存储专用数据中的数据。

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*/);

2 个答案:

答案 0 :(得分:3)

openFileInput会返回FileInputStream个对象。然后,您必须使用它提供的read方法从中读取数据。

// 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);

请查看FileInputStream以获取进一步的参考。请记住,这适用于文本文件...如果它是二进制文件,它会将奇怪的数据转储到您的小部件中。

答案 1 :(得分:3)

有很多方法可以在文本中阅读,但使用扫描仪对象是我最简单的方法之一。

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);

您需要import java.util.Scanner;才能使用此功能。如果您想从文件中获取更具体的信息,Scanner对象还有其他方法,如nextInt()