我正在尝试将一些简单文本保存在文件中,然后再阅读。
我已经在相同的应用程序中创建了文件,但工作正常,但由于某种原因,我得到了一个
当我尝试使用openFileInput()方法时FileNotFoundException
。
private static final String COOKIE = "account_cookie.txt";
public void saveAccountCookie(String accountId, String expiryDate) {
try {
PrintWriter pw = new PrintWriter(openFileOutput(COOKIE, MODE_PRIVATE));
pw.write(accountId + " " + expiryDate);
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public boolean cookieValid() {
try {
InputStreamReader isr = new InputStreamReader(openFileInput(COOKIE));
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;
}
}
这些方法是从AsyncTask
答案 0 :(得分:-2)
首先在源文件夹中创建一个Application Class,这样你就可以为应用程序本身处理General Stuff这样的东西
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;
}
}
告诉我这种方式是否有效。 :)