2016-02-10 119 views
0

我似乎遇到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」不是文件。我有點困惑,爲什麼現在正在發生......

+0

'ObjectOutputStream'與它無關,或者序列化。 – EJP

+0

@EJP它和它有關係它正在寫文件內容,你不能將文件內容寫入文件夾neds是一個文件。所以它應該拋出一個錯誤......但事實並非如此。 –

+0

否。該文件是否由'FileOutputStream'創建或寫入,是否寫入同上。 'ObjectOutputStream'是後來構建的,並沒有自己的I/O,全部刪除到FileOutputStream.Ergo它與它沒有任何關係 – EJP

回答

2

您致電f.mkdirs()正在創建一個路徑與您想要的文件路徑相同的路徑。改爲撥打f.getParentFile().mkdirs(),這應該清除它。

+0

因此,JDK 1.8改變了它,以便mkdirs現在忽略文件擴展名,然後... –

+1

我可能是錯的,但我認爲它沒有。至少,javadoc中的任何內容都不會回到1.5.0,這意味着它會將名稱中包含句點的名稱視爲文件而不是目錄...但是誰真的知道? :) – CodeBlind

+0

@MartinBarker它從來沒有。 – EJP