NetBeans Java Project from command line: Working directory is System32 - java

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...");
try
{
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.out.println(CustomMessages.systemExit());
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?

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);

You cannot rely on the current working directory to be set to anything.
Either provide the file as a class path resource instead or ask the jvm where the class is located in the file system and locate the file relative to that.
For a read only file I would consider providing it as a resource.

Related

Java JAR file runs on local machine but missing file on others

The JAR file consists of the ffmpeg.exe file and it can run normally on my machine without any problems. However, if I try to run it on another computer it would tell me that java.io.IOException: Cannot run program "ffmpeg.exe": CreateProcess error=2,The system cannot find the file specified from the stacktrace. The way I imported it was
FFMpeg ffmpeg = new FFMpeg("ffmpeg.exe"); //in res folder
...
//ffmpeg class
public FFMPEG(String ffmepgEXE) {
this.ffmepgEXE = ffmepgEXE;
}
The quick fix is you have to put ffmpeg.exe in the same folder with your .jar file.
If you want to read file from resources folder, you have to change this code:
URL resource = Test.class.getResource("ffmpeg.exe");
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath();
FFMpeg ffmpeg = new FFMpeg(filepath);

Java fails to create directory / file from the command line [duplicate]

This question already has an answer here:
Java error in making file through console
(1 answer)
Closed 4 years ago.
I have an executable that generates some file, and I need to call this executable from a Java application. The command goes like this
Generator.exe -outputfile="path/to/file" [some other params]
It works fine on the command prompt, but running it from Java,all steps are executed but the file is not created.
I doubt the problem was that my java application is not able to crate files / directories, so I tried to create a directory as below
try {
String envp[] = new String[1];
envp[0] = "PATH=" + System.getProperty("java.library.path");
Runtime.getRuntime().exec("mkdir path/to/folder", envp);
}
catch (Exception e) {
e.printStackTrace();
}
I get the following exception, even If the directory exist
java.io.IOException: Cannot run program "mkdir":
CreateProcess error=2, The system cannot find the file specified
I also tried using java.lang.Process and java.lang.Process and I got the same exception, although the command mkdir path/to/folder works fine on the command prompt
Two points:
1) You don't need to pass in the java.library.path to the mkdir command. Mkdir expects one parameter - the directory/ies you want to created.
2) Why not use the Java File class to create the directory instead? Create a File object of the path, then call the mkdirs() function on it.

Hot to set the working directory of a process in Java

I am trying to set the working directory of a process that will be running an exe.
Here is what I have so far:
public Process launchClient() throws IOException {
File pathToExecutable = new File(currentAccount.getAbsoluteFile()+"/Release", "TuringBot.exe");
System.out.println(pathToExecutable);
ProcessBuilder builder = new ProcessBuilder(pathToExecutable.getAbsolutePath());
builder.directory( new File( currentAccount, "Release" )); // this is where you set the root folder for the executable to run with
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
return builder.start();
}
but every time I launch it, the exe attempts to run but fails to because the current directory is wrong and it can't properly access the required files.
EDIT:
Here's a little more about whats going on...
I have x amount of client folders, each contains an executable file that needs to be started and relies on the contents of its local folder to execute properly, however when running this code to launch each executable file the working path for each unique executable is not being applied and is rather the default directory (the JAR's locations).

IOException when creating a temporary file?

I'm creating a task plugin for Atlassian Bamboo. At some moment of task executing, I would like to create a temporary file:
File temp = File.createTempFile(fileName.toString(), null, dir);
temp.deleteOnExit();
, where:
fileName.toString() = e.g. "C:\Atlassian\bamboo-home\xml-data\build-dir\CMPT-CMPTP-JOB1\test.java"
dir = new File("temp");
When testing this locally, everything works fine - the file is created properly. However, after I deploy plugin on server and try to execute above code, I've got an IOException:
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createTempFile(File.java:1879)
What could be the reason?
Additional info: I'm pretty sure that dir.exists() .
A file name of
"C:\Atlassian\bamboo-home\xml-data\build-dir\CMPT-CMPTP-JOB1\test.java"
is valid on Windows but is invalid on Unix operating systems. You won't be able to create a (temp) file like that, either as specified as the absolute name/path or the file nor just relative to another folder.
If your OS is Windows, you still can't use a full path (starting with drive specification like "C:") to be created as a child of another folder.
You could have spaces in the beginning or the ending of your path, print your file.getAbsolutePath() in order to see the current path where java is reading.
The dir variable must be set with the full (or relative) path to the directory temp. The first arg of File.createTempFile should be the prefix of the temp file (at least three letter long. for exeample "test"). This will create a "test.tmp" in the given directory (specified by the variable dir).
Check the javadoc
You can check existence of the directory dir with dir.exists()

exec, files location problem

In my jar application I do some calculations in exe program. When files and program.exe was in the same dir I used this command:
String[] str={"program.exe", "file1.txt", "file2.txt"};
pr = rt.exec(str);
and it worked great. But when I moved files to other dir and I try use this command:
String[] str={"program.exe", "temp\\file1.txt", "temp\\file2.txt"};
pr = rt.exec(str);
program.exe doesn't see files. What is more odd it start to see files when I change its names for anything else that default. file1.txt, file2.txt and temp are created in my jar program before program.exe start.
edit:
When problem started I try sth like this: default names file1.txt and file2.txt, I changed to aaa.txt and bbb.txt (in windows), and then:
String[] str={"program.exe", "temp\\aaa.txt", "temp\\bbb.txt"};
and it works.
edit2:
Now I know that problem is in program.exe. When I use it from command line (not from jar), like this:
program.exe temp\file1.txt temp\file2.txt
error:
FANN Error 1: Unable to open configuration file "temp\file1.txtÉ║#" for reading.
fann is artificial neural network library. When I copy files to program.exe dir:
program.exe file1.txt file2.txt
it works! When I changed files names in temp and do:
program.exe temp\file1aaa.txt temp\file2bbb.txt
it works also! So it is fann lib bug?
I'd use the ProcessBuilder api (it gives you much more control than Runtime.exec()) and I'd also use absolute paths:
File directory = new File("/path/tp/program.exe's/parent");
int returnCode = new ProcessBuilder("program.exe",
new File(directory, "temp/file1.txt").getAbsolutePath(),
new File(directory, "temp/file2.txt").getAbsolutePath()
)
.directory(directory).start().waitFor();
Give complete path of the filename and see. Something like below
String[] str = {"program.exe", "D:\\temp\\file1.txt", "D:\\temp\\file2.txt"};
If your OS is UNIX based then change it accordingly.
Have you tried relative path for finding the location
like
abc (folder)
-> code(folder)
-->Program.Java
-> temp
--> file1.txt
so
when u run ur program in Eclipse IDE
ur relative path will be from program.java file is
../temp/file1.txt
And try to use / instead of \ so that it wont take as an escape character.
when u run from a jar
You need to extract the temp folder from jar to outside
abc (folder)
-> jar (folder)
-->Program.jar
-> temp
--> file1.txt
OR
Read the jar content from the program as a zip file. Reach your temp folder inside it by code and then read the content as input stream.

Categories