gpt4 book ai didi

java - 将对象附加到android中的现有文件

转载 作者:行者123 更新时间:2023-11-30 04:41:48 25 4
gpt4 key购买 nike

我已将一个对象附加到现有文件,但我无法读取它,我可以读取第一个对象,这是我的代码有什么问题吗??

try{

FileOutputStream fos = openFileOutput("f.txt",MODE_PRIVATE | MODE_APPEND );

ObjectOutputStream oos = new ObjectOutputStream(fos);
String a=new String ("Hello object1 ");
String b=new String("Hello object2 ");
String c=new String("Hello object3 ");

oos.writeObject(a);
oos.writeObject(b);
oos.writeObject(c);
oos.close();

// Reading it back..

FileInputStream fis = openFileInput("f.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

//ois=new ObjectInputStream(fis);
// r=(String)ois.readObject();
String r;
while ((r= (String)ois.readObject()) != null) {
Log.i("while Read r",r);

Toast.makeText(getApplicationContext(),r, Toast.LENGTH_SHORT).show();
}

ois.close();

}catch (Exception e){
Log.i("Exception",e.getMessage());
}

希望你能帮帮我!!谢谢。

最佳答案

代码似乎是正确的,只是在“While”中做了一些修改,检查如下:

try{

FileOutputStream fos = openFileOutput("f.txt",MODE_PRIVATE | MODE_APPEND );

ObjectOutputStream oos = new ObjectOutputStream(fos);
String a=new String ("Hello object1 ");
String b=new String("Hello object2 ");
String c=new String("Hello object3 ");

oos.writeObject(a);
oos.writeObject(b);
oos.writeObject(c);
oos.close();

// Reading it back..

FileInputStream fis = openFileInput("f.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

//ois=new ObjectInputStream(fis);
// r=(String)ois.readObject();
String r;
while (fis.available() > 0) {
r= (String)ois.readObject();
Log.i("while Read r",r);

Toast.makeText(getApplicationContext(),r, Toast.LENGTH_SHORT).show();
}

ois.close();

}catch (Exception e){
Log.i("Exception",e.getMessage());
}

关于java - 将对象附加到android中的现有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5861510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com