Java 无法使用openFileOutput写入文件
我试图将一些简单的文本保存在一个文件中,然后稍后再阅读。 我已经在同一个应用程序中创建了工作正常的文件,但由于某种原因,我在这个应用程序中得到了一个Java 无法使用openFileOutput写入文件,java,android,Java,Android,我试图将一些简单的文本保存在一个文件中,然后稍后再阅读。 我已经在同一个应用程序中创建了工作正常的文件,但由于某种原因,我在这个应用程序中得到了一个 FileNotFoundException当我尝试使用openFileInput()方法时 这些方法是从一个AsyncTask调用的,首先在源文件夹中创建一个应用程序类,这样您就可以处理应用程序本身的常规内容 public class MyApp extends Application { private static MyApp inst
FileNotFoundException
当我尝试使用openFileInput()方法时
这些方法是从一个
AsyncTask
调用的,首先在源文件夹中创建一个应用程序类,这样您就可以处理应用程序本身的常规内容
public class MyApp extends Application {
private static MyApp instance;
public void onCreate() {
super.onCreate();
}
public MyApp() {
super();
instance = this;
}
public static MyApp getInstance() {
return (instance == null) ? instance = new MyApp() : instance;
}
}
那就这样试试
public void saveAccountCookie(String accountId, String expiryDate) {
try {
FileOutputStream fos = MyApp.getInstance().getBaseContext().openFileOutput(COOKIE, Context.MODE_PRIVATE);
PrintWriter pw = new PrintWriter(fos);
pw.write(accountId + " " + expiryDate);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public boolean cookieValid() {
try {
FileInputStream fis = MyApp.getInstance().getBaseContext().openFileInput(COOKIE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String[] cookie = br.readLine().split(" ");
br.close();
if (checkExpiry(cookie[1])) {
return true;
}
checkTrialRequest(cookie[0]);
return false;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}
告诉我这种方法是否有效。:) 我不认为拥有一个全局应用程序上下文与这个问题有什么关系。这只是一个好的实践,他应该使用FileInputStream和OutputStream,而不是直接使用StreamReader。我不认为拥有一个全局对象是一个好的实践。我不认为创建命名变量而不是使其保持匿名是一种更好的做法。我认为您应该关闭在
openFileOutput
中打开的FileOutputStream
。关闭PrintWriter
是不够的。我的印象是,当你关闭InputStream
或OutputStream
或类似的东西时,它也会关闭它包装的所有流?在签入代码后,你似乎是对的,pw.close似乎关闭了底层流。可能您必须刷新它?失败的文件和位置是什么?看看你是否能弄清楚为什么这个和那些有效的不同。这并不能解决它,方法.close()会刷新流,然后关闭。
public void saveAccountCookie(String accountId, String expiryDate) {
try {
FileOutputStream fos = MyApp.getInstance().getBaseContext().openFileOutput(COOKIE, Context.MODE_PRIVATE);
PrintWriter pw = new PrintWriter(fos);
pw.write(accountId + " " + expiryDate);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public boolean cookieValid() {
try {
FileInputStream fis = MyApp.getInstance().getBaseContext().openFileInput(COOKIE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String[] cookie = br.readLine().split(" ");
br.close();
if (checkExpiry(cookie[1])) {
return true;
}
checkTrialRequest(cookie[0]);
return false;
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
}