Why is my program denying access to create a file?
Asked Answered
A

2

5

In the book I'm reading on Java, it demonstrates serialization by using a program that writes to a file and stores it away. I'm getting a strange error that I don't know how to read and it denies me access to creating a .txt file. Here's the error:

Exception in thread "main" java.io.FileNotFoundException: C:\testFile.txt (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at serializableTests.MyProgram.main(MyProgram.java:18)

Here's the two classes for the program:

User class:

public class User implements Serializable {

    private static final long serialVersionUID = 4415605180317327265L;

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

And here's the main class:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;


public class MyProgram {
    public static void main(String[] args) throws IOException {
        User user = new User();
        user.setUsername("tpage");
        user.setPassword("password123");

        File file = new File("C:\\testFile.txt");
        OutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(user);
        System.out.println("I've store the user object in a file called " + file.getName());
    }
}

output

2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false 
2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false
2019-04-22 08:40:28,895 [main] INFO  g.t.service.impl.CsvServiceImpl - txn log file created data/test/tnx-log/tnc.log true 

2019-04-22 08:40:28,957 [main] INFO  g.t.service.impl.CsvServiceImpl - Directory structure created data/test/tnx-log/tnc.log false 
2019-04-22 08:40:28,957 [main] INFO  g.t.service.impl.CsvServiceImpl - file.getAbsoluteFile() : C:\Users\jigar\apps\workspace\trade-publisher\data\test\tnx-log\tnc.log canWrite() : false


@Override
    public void createTxnInfoFile() throws IOException {
        File file = new File(txnLogFile);
        if (!file.exists()) {
            boolean directoryStructureCreated = file.getParentFile().mkdirs();
            logger.info("Directory structure created {} {} ", txnLogFile, directoryStructureCreated);
            logger.info("file.getAbsoluteFile() : " + file.getAbsoluteFile() + " canWrite() : " + file.canWrite());
            boolean fileCreated = file.createNewFile();
            logger.info("txn log file created {} {} ", txnLogFile, fileCreated);
        }
        file = null;
    }
Anarchy answered 10/4, 2013 at 1:19 Comment(4)
What version of Windows are you using? The UAC can block in sorts of wonderful places and even silently. We had issues with File#canWrite returning true but then no file been written as well. As a side note, you never seem to be closing your streams, this may lock the fileLimbourg
I'm using Windows 7. Is that a problem?Anarchy
See mdma's answer (and close your streams ;))Limbourg
Try to run your java program with admin rights?Neon
G
13

On recent versions of Windows, you cannot write to the root folder of the system drive without elevated privileges.

To make it work, change the location to another drive or change to a subfolder in C, such as your profile directory, e.g. c:\users\yourname\testfile.txt

(Note that you're using a .txt ending but the file produced will not be readable in an editor. Serialization is a binary format.)

EDIT:

To implement this in code change

File file = new File("C:\\testFile.txt");

to something like

File file = new File("C:\\users\\bane\\testFile.txt");

I've used your SO name "bane" - replace with whatever your login name is on your pc.

Gallaway answered 10/4, 2013 at 1:24 Comment(5)
I'm not sure how to implement that into code, can you give me an example?Anarchy
So I took your advice with changing it to a subfolder, and although that worked, when I tried to open it in my OS(outside of eclipse) it showed up as this: ¬í sr serializableTests.User=Ga„A0_¡ L passwordt Ljava/lang/String;L usernameq ~ xpt password123t tpageAnarchy
Default java serialization is a binary format - no point loading it in a text editor. If you want to serialize to a text format, use XStream, which serializes to xml.Gallaway
Hey thanks so much, I actually used the double backspaces by accident and it worked and remembered my Python training and why you use 2 \\ instead of 1(most of the time). Thanks again, I appreciate it.Anarchy
@Bane You don't need backslashes at all in Java filenames. Use /.Adolf
F
0
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
    private File targetFolder;
    private int noOfFiles;
    public void copyDirectory(File sourceLocation, String destLocation)
            throws IOException {
        targetFolder = new File(destLocation);
        if (sourceLocation.isDirectory()) {
            if (!targetFolder.exists()) {
                targetFolder.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < children.length; i++) {
                copyDirectory(new File(sourceLocation, children[i]),
                        destLocation);

            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
            System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());            
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            noOfFiles++;
        }
    }

    public static void main(String[] args) throws IOException {

        File srcFolder = new File("C:\\sourcefolder\\");
        String destFolder = new String("C:\\destination\\");
        CopyFiles cf = new CopyFiles();
        cf.copyDirectory(srcFolder, destFolder);
        System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
        System.out.println("Successfully Retrieved");
    }
}
Foraminifer answered 11/12, 2014 at 9:36 Comment(1)
It is also helpful if you describe your solution.Duckling

© 2022 - 2024 — McMap. All rights reserved.