当谈到Android时,我目前处于初级阶段,目前我正面临一个我目前面临的问题。
我正在创建一个Android应用程序来检查内部存储中是否存在“cache.json”:
这是代码片段:
public class ShowClasses extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
filename = "cache.json";
file = new File(getApplicationContext().getFilesDir(), filename);
if (file.exists()) {
System.out.println("EXISTS");
} else {
System.out.println("DOES NOT EXIST");
writeFile();
}
readFile();
}
public void writeFile() {
new JsonTask().execute(email);
}
public void readFile() {
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int c;
result = "";
try {
while( (c = fin.read()) != -1){
result = result + Character.toString((char)c);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
private class JsonTask extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
result = ""; // Clear result
super.onPreExecute();
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
return "THIS STRING IS GOING TO BE RETURNED " + params[0];
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileout = null;
try {
fileout = new FileOutputStream(file);
fileout.write(result.getBytes());
//display file saved message
msg("File saved successfully!");
} catch (Exception e) {
e.printStackTrace();
}
try {
fileout.close();
} catch (IOException e) {
e.printStackTrace();
}
if (pd.isShowing()){
pd.dismiss();
}
}
}
}
我试图删除代码中不必要的部分,以便它的长度更小。
我面临的实际问题是何时调用writeFile()和readFile()。当我打开流时,我在readFile()中得到一个FileNotFoundException,即使应该创建该文件,因为在readFile()之前调用了writeFile()。
如果我在一次执行时写入文件然后在另一次执行时调用readFile(),它就会按原样运行。
这是我面临的错误。
System.err:java.io.FileNotFoundException:/data/user/0/host.timetable.timetablenotifier/files/cache.json(没有这样的文件或目录)System.err:at java.io.FileInputStream.open(Native Method) )
任何帮助将非常感激。
谢谢
writeFile()
是异步的。当该方法返回时,该文件没有发生任何事情。最多,你的onPreExecute()
的JsonTask
可能被称为。因此,当您调用readFile()
时,该文件尚不存在。
除此之外:
AsyncTask
中使用的writeFile()
,但你在onPostExecute()
中执行磁盘I / O,并且在主应用程序线程上调用该方法。readFile()
的主应用程序线程上执行磁盘I / O.int
的数据并不是建议接近20年的方法。AsyncTask
和ProgressDialog
都不会考虑配置更改也:
getApplicationContext().getFilesDir()
,getFilesDir()
可以被onCreate()
取代createNewFile()
AsyncTask
在后台线程中运行,因此主线程中的其他代码不会等待执行完成。简单来说,你的readFile()
方法在writeFile()
完成之前执行,因此有一个FileNotFoundException
。什么对你有用,如果你把readFile()
方法放在你的onPostExecute()
内的Asynctask
方法的末尾