Java 的测试程序,这是类下边第一句,前边没有其他操作:FileInputStream fin = new FileInputStream("friend.list");
ObjectInputStream oin = new ObjectInputStream(fin);
m_map = (HashMap)oin.readObject();
fin.close();
oin.close();文件friend.list是自己手动新建的一个空白文件,然后命名。我确定文件位置没有问题,但就是在后边读不出文件,在这段就报错。是不是FileInputStream fin = new FileInputStream("friend.list");ObjectInputStream oin = new ObjectInputStream(fin);对文件本身格式有要求?谢谢!
ObjectInputStream oin = new ObjectInputStream(fin);
m_map = (HashMap)oin.readObject();
fin.close();
oin.close();文件friend.list是自己手动新建的一个空白文件,然后命名。我确定文件位置没有问题,但就是在后边读不出文件,在这段就报错。是不是FileInputStream fin = new FileInputStream("friend.list");ObjectInputStream oin = new ObjectInputStream(fin);对文件本身格式有要求?谢谢!
String name = new String("China");
String password = new String("********"); String fileName = "data.txt"; FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(name);
oos.writeObject(password);
oos.close();
fos.close(); FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
String str = (String) ois.readObject();
System.out.println(str);
str = (String) ois.readObject();
System.out.println(str);
str = (String) ois.readObject(); // 注意,这里有异常发生,因为只写入了2个对象,而读取了3个对象,读取第3个对象时发生异常,这说明,能正常读取到的对象,必须是用ObjectOutputStream写入文件的,因为每个对象之间有一些不可见的分隔符,打开文件就看到了,最好用十六进制打开.
System.out.println(str);
ois.close();
fis.close();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;public class TestInt { public static void main(String[] args) throws Exception {
File objFile = new File("data.txt");
objFile.deleteOnExit();
if (objFile.createNewFile())
System.out.println("生成对象文件成功"); // 测试HashMap
Map testMap = new HashMap();
testMap.put("name", "China");
testMap.put("psw", "1234567"); FileOutputStream fos = new FileOutputStream(objFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(testMap);
fos.close();
oos.close();
System.out.println("保存对象成功"); HashMap resultMap = null;
FileInputStream fis = new FileInputStream(objFile);
ObjectInputStream ois = new ObjectInputStream(fis);
resultMap = (HashMap) ois.readObject();
System.out.println(resultMap.get("name"));
System.out.println(resultMap.get("psw")); }
}