我是Android編程的初學者。 我想提供一個窗體給用戶輸入一些信息。 我想將該信息寫入文件,然後從文件中讀取並在TextView
中顯示。目前,我讀到的是null
。你能幫我解決這個問題嗎? 的代碼是這一個:Android - 從文件讀取和寫入
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// write
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
try {
writeToFile(s.toString().getBytes(), file);
} catch (IOException e) {
e.printStackTrace();
}
// read from file and show in text view
Context context = getApplicationContext();
String filename = "config.txt";
String str = readFromFile(context, filename);
String first = "You have inputted: \n";
first += str;
textView.setText(first);
}
});
寫功能:
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush();
bos.close();
}
catch (Exception e) {
}
}
}
}
讀取功能:
public String readFromFile(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
您確定您使用正確的文件路徑嗎? –
如果我沒有,我會有一個錯誤。但我沒有錯誤也沒有警告 –