signus
signus

Reputation: 1148

Current path and inputting files

I'm writing a fairly simple Java program, and some options I require from the user give them the ability to read from a list of text for data comparisons.

What I would like to do is to give them the ability to simply define the file if it is in the current working path, and assume so unless they provide a separate path to their file. I'd like to use the same approach to generate a output file wherever they define.

So I start by checking if the file even exists (which does not work if you do not define a full path):

File f1 = new File(inputFile);
        if(f1.exists())
            System.out.println("Exists");
        else if(!f1.exists())
        {
            System.out.println("Cannot find file " + inputFile);
            System.exit(1);
        }

So I could create the file with new File(path/inputFile), but I can break that fairly easily.

I want them to be able to do any of the following:

program.exe -m -1 inputFile.txt outputFile.txt

program.exe -m -1 C:\Users\tmp\Desktop\inputFile.txt outputFile.txt

program.exe -m -1 inputFile.txt C:\outputFile.txt

Any suggestions on where I might make my next step?

Upvotes: 0

Views: 83

Answers (1)

OscarG
OscarG

Reputation: 395

you can try something like

String currentUserPath = System.getProperty("user.dir")

to get the current path from where the application is being ran. Then you can check if the user provided on args[0] a full path, something like:

String inputPath = args[0];
inputPath = inputPath.trim().toLowerCase(); // as you are using windows case doesn't matter    
if (!inputPath.startsWith("c:"))
    inputPath = currentUserPath + inputPath;

and you could do something similar for the outputFile

Upvotes: 1

Related Questions