我是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 "";
}
}
您确定您使用正确的文件路径吗? –
如果我没有,我会有一个错误。但我没有错误也没有警告 –