E. Rowlands E. Rowlands - 1 year ago 94
Java Question

NetBeans Java Project from command line: Working directory is System32

If I run my Java program in NetBeans and follow the information given in the output window to run from a command line:

To run this application from the command line without Ant, try:
java -jar "C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\assignment2.jar"

The program starts to run, but when it comes to run the following code to open a .txt file (my "database"):

System.out.println("Loading database of stored transactions...");
file = new File("TransactionDetails.txt");
inFile = new Scanner(file);
// if the log couldn't be found in the default program location
catch (FileNotFoundException ex)
System.out.println(CustomMessages.FileNotFound() +
System.getProperty("user.dir")); // display default directory
System.exit(1); // the program needs the log to function as intended

It cannot find the .txt file and prints the default directory as the Windows System32 folder. How can I specify the location to be the Project folder as expected?

Answer Source

You could use an absolute path to the file instead of a relative path. e.g

file = new File("C:\Users\erdik\OneDrive\Documents\Computing Science Degree\Course Folder\Year 1\Programming 1\Assignment 2 - Year 2 Edit\assignment2\dist\TransactionDetails.txt");
inFile = new Scanner(file);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download