我似乎遇到1.8 JDK這個項目使用1.7 JDK構建的問題,但我遇到了一個我不太明白的問題。Java 1.8 FileOutputStream創建目錄
所以我有一個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;
}
}
}
但是當寫入方法被調用它的一些原因是創造目錄EG
讀取文件:
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
@EJP它和它有關係它正在寫文件內容,你不能將文件內容寫入文件夾neds是一個文件。所以它應該拋出一個錯誤......但事實並非如此。 –
否。該文件是否由'FileOutputStream'創建或寫入,是否寫入同上。 'ObjectOutputStream'是後來構建的,並沒有自己的I/O,全部刪除到FileOutputStream.Ergo它與它沒有任何關係 – EJP