2010-06-25 165 views
2

有人可以帮助我解释如何读取和显示存储在设备内存上的内部存储 - 私有数据中的数据。内部存储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*/); 

回答

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作进一步的参考。请记住,这将适用于文本文件...如果它是一个二进制文件,它会将奇怪的数据转储到您的小部件中。

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;这个工作。扫描仪对象还有其他方法,如nextInt(),如果您想从文件中获取更多特定信息。