2010-06-25 166 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(),如果您想從文件中獲取更多特定信息。