【发布时间】:2017-06-02 17:50:11
【问题描述】:
您好,我的代码有两个按钮 Save 和 Read,当我按下 save 时,它会将数据保存到 SampleFile.xml,当我按下 load 时,xml 文件的内容会显示在设备的屏幕上。我的应用程序工作但当我试图找到 SampleFile.xml 时无处可去。我尝试将我的应用程序用于模拟器和物理设备
public class MainActivity extends Activity {
EditText inputText;
TextView response;
Button saveButton,readButton;
private String filename = "SampleFile.xml";
private String filepath = "MyFileStorage";
File myExternalFile;
String myData = "<question> "+ Test.s +" <qusetion>\n";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputText = (EditText) findViewById(R.id.myInputText);
response = (TextView) findViewById(R.id.response);
saveButton =
(Button) findViewById(R.id.saveExternalStorage);
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(myData.toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText("");
response.setText("SampleFile.xml saved to External Storage..");
}
});
readButton = (Button) findViewById(R.id.getExternalStorage);
readButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.xml data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
}
【问题讨论】:
-
你永远不会初始化
myExternalFile变量。 -
尝试使用记录用于存储文件的路径进行打印。像这样:Log.d("PATH",new File(getExternalFilesDir(filepath), filename));
-
@lionscribe 是的,他在这一行:myExternalFile = new File(getExternalFilesDir(filepath), filename);
-
运行应用时会发生什么?
-
为什么不直接设置断点,在运行时查看路径呢?还是只记录路径?