IOException at java.io.File.createNewFile();

丶灬走出姿态 提交于 2020-01-24 14:25:28

问题


I do have some code for serialization which does not work. I have tried to insert both CanRead() and CanWrite() in if-statements which showed they did not have permissions to read and write. I have also tried to insert 'java.io.File.setReadable' and 'java.io.File.setWriteable to true but it still throws the error.

The code is as following:

public static void save(Object obj, String filename) throws FileNotFoundException, IOException
{
    File f = new File("c:/DatoChecker/" + filename);
    File dir = new File("c:/DatoChecker");
    if(!dir.exists())
        dir.mkdirs();
    f.setReadable(true);
    f.setWritable(true);
    if(!f.exists())
    {
        f.createNewFile();
    }
    FileOutputStream op = null;
    ObjectOutputStream objectStream = null;
    op = new FileOutputStream(f);
    objectStream = new ObjectOutputStream(op);
    objectStream.writeObject(obj);
    objectStream.close();
}

public static Object fetch(String filename) throws FileNotFoundException, IOException, ClassNotFoundException
{
    File f = new File("c:/DatoChecker" + filename);
    File dir = new File("c:/DatoChecker");
    if(!dir.exists())
        dir.mkdirs();
    f.setReadable(true);
    f.setWritable(true);
    if(!f.exists())
    {
        f.createNewFile();
    }
    FileInputStream ip = null;
    ObjectInputStream objectStream = null;
    Object obj = null;
    ip = new FileInputStream(f);
    objectStream = new ObjectInputStream(ip);
    obj = objectStream.readObject();
    ip.close();
    objectStream.close();  
    return obj;
}

Stacktrace:

SEVERE: null
java.io.IOException: access denied
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:947)
    at com.check.me.Serialization.fetch(Seralization.java:39)
    at com.check.me.GoodsList.load(GoodsList.java:82)
    at com.check.me.START.main(START.java:22)

The one for save is congruet from GoodsList (just save instead of load) and up but it is quite a bit longer below so I will leave it out for now.

Thanks for the help beforehand
Highace2


回答1:


You state that you did not have permission to read or write. And, indeed, you get an error telling you that you don't have permission. You need to change the ACL on the directory in which you are creating the file, or pick a different directory.



来源:https://stackoverflow.com/questions/14798787/ioexception-at-java-io-file-createnewfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!