Saman Gholami
Saman Gholami

Reputation: 3512

Run Existing Project That Uses some Static Files

I've created this class for access/create some files:

public static File getFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (file.exists() && !file.isDirectory()) {
            return file;
        } else {
            file.createNewFile();
            byte[] dataToWrite = "some text".getBytes();
            FileOutputStream out = new FileOutputStream(file);
            out.write(dataToWrite);
            out.close();
            return file;
        }

    }

I'm calling the class this Way:

getFile("myfile.txt");

The application tries to access the file, if there isn't specific file, it'll be created. The problem is when I run this code under non-admin account, I'll get IOException for permission issues. I know that the file will be created in eclipse folder. Also I shouldn't use static file path for my project, It should work dynamically. What should I do?

Upvotes: 0

Views: 42

Answers (2)

E-Riz
E-Riz

Reputation: 33044

Unless this is a class assignment, I would not write low-level File code any more. Look at Apache Commons IO and/or Google Guava.

Also, without any more detailed path, the file is looked for (and created) in whatever location the app is run in. In Eclipse, that's the project's root folder by default, you can change it in the Launch Configuration. Launch Configurations are created automatically when you do Run as... on a project or file; they can be edited via the Run > Run Configurations... or Run > Debug Configurations... menu. Note that Run and Debug configurations are actually the same under the covers, the only difference is how Eclipse launches the JVM (either in debug mode or not).

You can also invoke and/or edit them via toolbar buttons: enter image description here

See more info at http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-java-local-configuration.htm

Upvotes: 1

Rafael Larios
Rafael Larios

Reputation: 191

Regarding the permission issue there is no going around that. You should capture the Exception and interact with the user telling that the user doesn't have permission and should/could provide another path.

You have to capture the path from the user maybe from the console, application parameters or another file.

One of the options is to capture the arguments when the application is called, for example:

public static void main (String args [])
{
    //First argument is the file path
    String path = args[0]; 
    File theFile = null;

    if(args[0] != null){
        try{
            File theFile = File getFile(path);
            //do stuff with the file
        }catch(IOException ioe){
            //NManage the Exception here
        }

    }
}

Upvotes: 0

Related Questions