java寫文件時如果不存在自動創建


public static boolean writeObject(String filePath, Object object){
    try{
        File file = new File(filePath);
        file.createNewFile();//noly create when the file is not exist
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return true;
    }catch(Exception e){
        e.printStackTrace();
        return false;
    }
    finally{
        try{
            if(objectOutputStream!=null){
                objectOutputStream.close();
            }
            if(fileOutputStream=null){
                fileOutputStream.close();
            }
        }catch(Exception e2){

        }
    }
}

解決此問題一種比較推薦的方式是使用file.createNewFile();

當文件已經存在時,此方法不會對文件產生任何影響。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM