我是Android程序的初学者。我试图提供一个表单给用户输入一些信息。我想将这些信息写入文件中,然后从文件中读取并在TextView中显示。目前,我读到的是null。你能帮我解决这个问题吗?代码是这个:
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 "";
}
}发布于 2017-05-27 16:20:07
Edittext的getText()方法返回editable。因此,首先应该使用toString()函数将其转换为字符串。并检查您是否已给予WRITE_EXTERNAL_STORAGE许可。
发布于 2017-05-27 15:31:48
如果我没有遗漏你写的东西
String extStorageDirectory =
Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");但你读到了
FileInputStream fis = context.openFileInput(filename);后者在应用程序基目录中使用dir,而输出则转到外部strage目录的基dir。
为什么不使用context.openFileOutput()而不是getExternalStorageDirectory()
如果文件应该存储在外部,请尝试如下:创建File对象的方式保持不变。请使用FileOutputStream fos = new FileOutputStream(file);代替FileInputStream (用于写作)。请记住在清单中设置适当的权限。在哪些条件下,它们是必要的,请咨询Android文档。
https://stackoverflow.com/questions/44218413
复制相似问题