我似乎遇到了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");
我最终得到了空目录&#34; Global.cfg.bin&#34;不是文件。我有点困惑为什么现在正在发生......
答案 0 :(得分:2)
您对f.mkdirs()
的调用是创建一个路径,其路径与您想要的文件路径相同。请改为调用f.getParentFile().mkdirs()
,然后清除它。