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

11,235

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.

Share:
11,235
Zinoex
Author by

Zinoex

Updated on June 14, 2022

Comments

  • Zinoex
    Zinoex almost 2 years

    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