我正在处理一个android项目,我有两个对象需要保存和读取。到目前为止,我已经为其中一个对象编写了代码,但是当我运行它时,我得到了错误"java.io.FileNotFoundException: tripfile.ser: open : ENOENT (没有这样的文件或目录)“。
我发现这个post也有类似的问题,但是那里的解决方案似乎对我没有用。我的密码在下面。
public class FileHandler {
static Context context;
static String tripFileName = "tripfile.ser";
static String oauthFileName = "oauthFile.ser";
public FileHandler(Context c){
context=c;
File dir = new File(context.getFilesDir() + "C:/Users/M/workspace/NerdRanch/FitTravel");
dir.mkdirs();
File tripFile = new File(dir, tripFileName);
File oauthFile = new File(dir, oauthFileName);
}
public static void writeTrip(Trip curTrip){
Trip trip = curTrip;
FileOutputStream outputStream;
try {
outputStream = context.openFileOutput(tripFileName, 0);
ObjectOutputStream objectStream = new ObjectOutputStream(outputStream);
objectStream.writeObject(trip);
objectStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Trip readTrip(){
Trip t;
try{
FileInputStream inputStream = new FileInputStream(tripFileName);
ObjectInputStream objectIn = new ObjectInputStream(inputStream);
t = (Trip) objectIn.readObject();
objectIn.close();
return t;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
}有人能告诉我我做错了什么吗?或者指给我一个有用的相关帖子?
发布于 2015-05-18 18:41:22
尝试此方法将对象写入和读取到共享prefs文件中,-it使用google的gson来序列化对象,并使用共享pref编写对象。
..。这很容易
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;要编写对象:
SharedPreferences mPrefs;
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(object);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();若要读取对象:
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject object = gson.fromJson(json, MyObject.class);发布于 2015-05-18 18:43:27
"C:/Users/M/workspace/NerdRanch/FitTravel"这是windows机器上的文件或目录。如果你拿着手机在灌木丛里跑来跑去,你认为可以找到它吗?此外,C:不存在于Android/linux文件系统中。并且:字符是被禁止的。
https://stackoverflow.com/questions/30310062
复制相似问题