【发布时间】:2016-05-21 13:13:22
【问题描述】:
我似乎对 1.8 JDK 有问题,这个项目是使用 1.7 JDK 构建的,但我遇到了一个我不太明白的问题。
所以我有一个 ConfigReader 类。
public class ConfigReader {
private static ConfigReader _inst;
public static ConfigReader GetInstance(){
if(_inst == null){
_inst = new ConfigReader();
}
return _inst;
}
private String basePath = "Config/";
public <T extends Serializable> void Write(T in, String filename)
{
String path = basePath+filename+".bin";
try
{
File f = new File(path);
f.mkdirs();
FileOutputStream fileOut =
new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(in);
out.close();
fileOut.close();
System.out.println("Saved config file '"+path+"'");
}catch(IOException i)
{
System.out.println("Failed to create config file '"+path+"'");
}
}
public boolean ConfigExists(String filename)
{
String path = basePath+filename+".bin";
File finfo = new File(path);
return finfo.exists();
}
public <T extends Serializable> T Read(T readin, String filename)
{
String path = basePath+filename+".bin";
try
{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
readin = (T) in.readObject();
in.close();
fileIn.close();
return readin;
}catch(IOException i)
{
System.out.println("Failed to read '"+path+"'");
return null;
}catch(ClassNotFoundException c)
{
System.out.println("Failed to unserialize '"+path+"'");
c.printStackTrace();
return null;
}
}
}
但由于某种原因,当调用 Write 方法时,它正在创建目录 E.G
读取文件:
boolean cfgExists = ConfigReader.GetInstance().ConfigExists("Global.cfg");
if(_inst == null && !cfgExists){
_inst = new Global();
}else if(cfgExists){
_inst = ConfigReader.GetInstance().Read(_inst, "Global.cfg");
}
编写文件:
ConfigReader.GetInstance().Write(this, "Global.cfg");
我最终得到的是空目录“Global.cfg.bin”而不是文件。我有点困惑为什么现在会发生这种情况......
【问题讨论】:
-
ObjectOutputStream与它无关,也与序列化无关。 -
@EJP 好吧,它与它有关,它正在写入文件内容,您不能将文件内容写入需要成为文件的文件夹中。所以它应该抛出一个错误......但它不是。
-
没有。该文件由
FileOutputStream,创建或不创建,并写入或不写入,同上。ObjectOutputStream是在之后构建的,没有自己的 I/O,将其全部交给FileOutputStream.Ergo,与它无关
标签: java io java-io fileoutputstream