我在Android应用程序上进行了读写操作。在onCreate上,将读取文件并将其显示为editext并可进行编辑。按下保存后,数据将写入将在onCreate上读取的同一文件。但是我收到了一个错误。目录中没有这样的文件。我不明白。我按下保存按钮时创建文件。有什么想法吗?
Java代码:
EditText Name;
EditText Age;
EditText Height;
EditText Weight;
EditText MedHistory;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalhistory);
Name = (EditText) findViewById(R.id.medhistName);
Age = (EditText) findViewById(R.id.medhistAge);
Height = (EditText) findViewById(R.id.medhistHeight);
Weight = (EditText) findViewById(R.id.medhistWeight);
MedHistory = (EditText) findViewById(R.id.MedHist);
int i = 0;
String MedHistData[] = new String[5];
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
MedHistData[i] = aDataRow;
i++;
}
i = 0;
Name.setText(MedHistData[0]);
Age.setText(MedHistData[1]);
Height.setText(MedHistData[2]);
Weight.setText(MedHistData[3]);
MedHistory.setText(MedHistData[4]);
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Button Save = (Button) findViewById(R.id.SaveBtn);
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(Name.getText() + "\n");
myOutWriter.append(Age.getText() + "\n");
myOutWriter.append(Height.getText() + "\n");
myOutWriter.append(Weight.getText() + "\n");
myOutWriter.append(MedHistory.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Medical History Saved'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
答案 0 :(得分:1)
您应该使用openFileInput()方法打开文件进行读取,使用openFileOutput()进行写入。这些函数分别返回FileInputStream和FileOutputStream。
答案 1 :(得分:0)
我的猜测:您没有该文件的写入权限。 您只能访问特定文件夹以便在android中编写。 看看
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
他们有一个关于如何编写文本文件的简单示例。