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

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.

Related

Running .JAR file from java code (netbeans)

Im trying to run a jar file from java code, But unfortunately does not success.
A few details about the jar file:
The jar file located in a different folder (For example - "Folder").
The jar file using a files and folders are in the root folder (the same "Folder" i mentioned above).
What im trying to do so far:
JAR file project.
In netbeans i checked that the main class are defiend (Project properties -> Run -> Main Class).
Other JAVA program
Trying to run with the command:
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar");
&&
Runtime.getRuntime().exec("javaw -jar "C:\\Software\\program.jar" "C:\\Software");
The jar file opened well, But he doesnt know and recognize his inner folders and files (the same "Folder" i mention above).
In short, it does not recognize its root folder.
Trying to run with ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start", "javaw", "-jar", "C:\\Software\\program.jar");
pb.directory(new File("C:\\Software"));
try {
pb.start();
} catch (IOException ex) {
}
In Some PC's its works fine, But in other pc's its not work and i got an error message: "Could not find the main class"
** Offcourse if i run the jar with double click its works.
So how can i run a jar file from other java program ?
Use this variant of .exec where you specify working folder as the third argument. (In your examples, you always only use one argument.)
exec("javaw -jar "C:\\Software\\program.jar", null, "C:\\Software");
You can try to call it something like below. There are 2 types of calling it.
public class JarExecutor {
public static void main(String[] args) throws IOException, InterruptedException {
//This is first way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-jar" ,"C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar"});
//This is second way of calling.
Process proc=Runtime.getRuntime().exec(new String[]{"java","-cp","C:\\Users\\Leno\\Desktop\\JarsPractise\\JarsPrac.jar","com.shiva.practise.FloydTriangle"});
proc.waitFor();
BufferedInputStream is=new BufferedInputStream(proc.getInputStream());
byte[] byt=new byte[is.available()];
is.read(byt,0,byt.length);
System.out.println(new String(byt));
}
}

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

Get working directory of another Java process

I can get working directory of current Java program using this code:
Path path = Paths.get(*ClassName*.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Also I can get CommandLine parameters (but there is no directory in the output) of running Java processes using this command wmic process get CommandLine where name='java.exe' /value
It is possible to get working directory of another Java process (better programmatically)? Probably it can be solved with some jdk/bin utilities?
You can get this information via the Attach API. To use it, you have to add the tools.jar of your jdk to your class path. Then, the following code will print the current working directories of all recognized JVM processes:
for(VirtualMachineDescriptor d: VirtualMachine.list()) {
System.out.println(d.id()+"\t"+d.displayName());
try {
VirtualMachine vm = VirtualMachine.attach(d);
try(Closeable c = vm::detach) {
System.out.println("\tcurrent dir: "+vm.getSystemProperties().get("user.dir"));
}
}
catch(AttachNotSupportedException|IOException ex) {
System.out.println("\t"+ex);
}
}

Unable Create Directory in CentOS using Java [duplicate]

This question already has answers here:
Unable to create the directory error
(6 answers)
Closed 6 years ago.
I'm creating a Web Application using Java Servlets. I used JDK7, Tomcat7. I was perfectly working till I hosted local site in windows. But when I migrated to CentOS directory is Not creating.
File outputFile = new File("/Data/");
try{
if(!outputFile.exists()){
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}else{
outputFile = new File("/Data/" + user);
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}
}
}else{
outputFile = new File("/Data/" + user);
if(!outputFile.exists()){
if(!outputFile.mkdir()){
throw new UnableToCreateFolderException();
}
}
}
This is the code I used in Windows. And I tried to create "/Data" directory and give full access to user and then I tried to run it.
That path (/Data) is in the root directory, which the user you're running Tomcat as certainly shouldn't have write access to. It's always bad design to hard-code paths like this in your program; instead, you should read a property (such as myapp.homedir) and use that instead.
Just execute this command and try again,
chmod 755 /Data
chmod 777 /Data/*

How to run a Mac application From Java?

I tried the code below to run a stand-alone utility app I created from Apple script but, I get a No File or Directory Exists error.
I put identical copies (for testing) in the project, dist, parent directories but, it didn't help.
So, my questions are:
Is my call to run the app bad (perhaps because it's not a Windows exe)?
How to run a mac app from java?
Thanks
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Runtime r=Runtime.getRuntime();
Process p=null;
String s="MyLineInInput.app";
try {
p = r.exec(s);
} catch (IOException ex) {
Logger.getLogger(AudioSwitcherView.class.getName()).log(Level.SEVERE, null, ex);
}
}
A Mac App Bunde is not an executable file, it's a folder with a special structure. It can be opened using the open command, passing the App Bundle path as an argument: open MyLineInInput.app.
EDIT:
Even better would be using Desktop.getDesktop().open(new File("MyLineInInput.app"));
I used the Runtime.getRuntime().exec() method with the open command mentioned in the selected answer. I didn't use Desktop.getDesktop().open() since it unwantedly opened a terminal in my case and I didn't want to create an extra File object.
Process process = Runtime.getRuntime().exec("open /System/Applications/Books.app");
Reason for adding '/System':
It seems we need to use the /System prefix for System apps. For user-installed apps, that's not required, and it can be like /Applications/Appium.app.
To answer #Pantelis Sopasakis' issue that I also faced initially -
I get the error message: java.lang.IllegalArgumentException: The file: >/Applications/Microsoft Office 2011/Microsoft\ Excel.app doesn't exist.
In this case, it could be simply due to not escaping the space characters in the path.
Environment: JDK 11 Zulu - macOS Monterey 12.2.1 - M1 Silicon

Categories