Shell script java program not writing files correctly - java

I have a java program that syncs the content of two directories. The program takes the two directories as arguments.
I created a shell script to run the program on Linux. When the program firsts runs it creates a .sync file in each directory, this work perfectly on windows but is causing me some issues on linux. I'm very new to linux so unsure what is really going on.
My program uses the following piece of code to create the .sync file...
FileWriter fileDir1 = new FileWriter(dir1 + "\\.sync");
fileDir1.write(obj.toJSONString());
fileDir1.flush();
fileDir1.close();
When I run the program on linux the files are being created in the same directory as the two directories are located instead of inside the two directories. The resulting files look like this..
dir1\.sync and dir2\.sync
Any help would be great.

Use a forward slash / instead of an escaped backslash \\, it works both on Windows and Linux.
FileWriter fileDir1 = new FileWriter(dir1 + "/.sync");

Related

How to run a C++ exe file from Java?

I want to open an EXE file from a Java program. I tried 2 procedures.
The program can run some programs, like NotePad++, but cannot run my C++ EXE file. I tried:
Process exec = Runtime.getRuntime().exec(file.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder(file.getAbsolutePath());
but neither of the above work. No exception is thrown, and exec.isAlive = true.
Your mistake is that you took the absolute path in the first procedure.
Try using a relative path, I just tested and it worked just fine.
This also works for me (using 2 backslashs').
Runtime.getRuntime().exec("C:\\Program Files\\DDNet\\DDNet.exe");
Kind regards

Why does my batch file give an error if it has spaces in path?

I am trying to run a .jar file using a .bat file. But my Batch file gives an error when I have spaces in my path.
For e.g.
#echo off
java -jar %~dp0\..\new\myFile.jar %*
This are the contents of my batch file. I know that %~dp0 will give the current drive letter and path to my batch file and then \..\ will go back to it's parent directory and then it will open the new directory and run the jar file from it.
But the problem here is if my path contains a space in it the batch file gives an error:
Error: Unable to access jarfile C:\Users\Vatsal
Assuming my path for .jar file is:
C:\Users\Vatsal Sura\myFolder\new\myFile.jar
and path for my .bat file is:
C:\Users\Vatsal Sura\myFolder\batch\batchFile.bat
Now if I move myFolder directly in C:\, which doesn't contain any spaces in it, then it won't give any error and the .jar file would run as expected.
I want to know why this is happening and what should I do to make spaces count in my path?
Put the offending part in double quotes: java -jar "%~dp0\..\new\myFile.jar" %*
If the expansion is C:\Users\Vatsal Sura\myFolder\new\myFile.jar, then without quotes, -jar is only seeing up to the first space as it's argument (i.e. -jar C:\Users\Vatsal) and the remainder (Sura\myFolder\new\myFile.jar) is a completely different argument not related to the -jar
You need to make the shell/cmd see all of that as one argument. Double quotes will still allow any expansion to happen but everything within the quotes will be seen as a single item (the quotes won't be there when java sees it).
The reason for your problem is simple
Batch Is Simple Too,
Windows needed to create command Line, powershell, blah blah, and with its awesome features. However, Batch only runs on one programmed line of code, yes its confusing lol but when you write the code it is nothing compared to the binary. Batch is not too advanced and therefore does not process spaces when its in the "heart" of the command, like it i do this it literally has the same error however batch can tell the difference:
ec ho
(supposed to be echo)
anyways, a simple solution to your problem can be changing the encoding that your batch file is working on or just simply taking out the spaces on you directory.
Plus, don't use
%~dp0\
(it suKs)
Instead, to simplify this just do
#echo off
java -jar %CD%\new\myFile.jar %*
you don't have to even set %CD% to be anything it just automatically used the current directory.
*even with all this, your initial problem will not be solved. It may if you change the encoding (use notepad++ for that) but i hope you found this answer at least a little helpful to explain how this is working.

Controlling output file of a java jar using command line

I am using a .jar file, but unfortunatley as a black box, i.e. I do not know what exactly is in there nor how it all works.
I am sending commands to the Mac terminal from a Python script. I enter the following command:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt
This does what I need: analyses input using the 'black box' and creates and new file with analysis output. This new file is created in the folder where jarfile.jar is located.
I want to have this file put somewhere else upon creation.
I have tried using the > operator, specifying a path, e.g.:
java -jar jarfile.jar req_data /abs_path/to/required/data input path/to_my_/input/file.txt > /output/path/
this created a file in my desired location, but it was simply the message from Terminal, saying "The operation was carried out successfully" - the analysis results file was created in the same folder as before.
I tried %*> too, but it threw an error.
As a poor workaround I now have a function, which retrospectively finds and moves all the newly created files (analysis output) to my desired folder.
Is there a way to control the output files with the command line within the original command? Or is it something that is specified somewhere in my jar file? My problem is that editing it is not allowed.
I'm new to python. However, I may suggest to try few things, if they can work for you. Apology me, if does not work! I believe that you have already done the following step:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
Like, if you have a properly configured jar path, then can run jar directly.
Secondly, look at the cwd parameter (is used for executable). Include a cwd param as x
def run_command(command, **x):
with subprocess.Popen(command,...., **x) as p:
for run_command specify the path of either the working directory (possibly it should be) or the full system path. I'm not sure, just try both.
for outputline in run_command(r'java -jar jarfilepath', cwd=r'workingdirpath', universal_newlines=True):
print(outputline, end='')
Alternatively, you can try to run command from the directory in which you wish to store output file. Try: run the popen as
subprocess.Popen(r'directory of running command', cwd=r'workingdir')
where workingdir could be your current directory path.
If it does not work, try without r'. If still does not work, try doubling slash in the path like (C:\\ abc\\def)

Accessing external files within Java applications under Windows and Linux Operating Systems

Please I am facing the following issue:
Throughout my Java program, i am accessing some files which it seems they are being accessed in a different way under windows compared to Linux. For example, if i wanted to access the following file within the same folder as the project i would write the following:
Under Linux: File Operations_File = new File("Data/Operations.txt");
Under Windows: File Operations_File = new File("Data\\Operations.txt");
I will be needing a standard methodology that works under all operating systems (or at least those two). As coding two versions of my code is not elegant at all.
My Two operating system that I am operating on are: Linux Mint 9 and Windows XP. I used NetBeans 6.9.1 throughout all the project.
Your help is greatly appreciated!
File.separator is exactly for this.
File f = new File("Data" + File.separator + "Operations.txt");
Don't get confused with File.pathSeparator, that is used to separate paths from each other. For example:
/usr/local/lib:/usr/lib:/var/lib
In the above example, : is the path separator (windows uses ; for path separators).
You can also create a File representing the directory and another File representing something in that directory like this:
File dataDir = new File("Data");
File operationsFile = new File(dataDir, "Operations.txt");
You could also skip the File for the directory and just do this as well:
File operationsFile = new File("Data", "Operations.txt");
Under Windows, printing out operationsFile gives Data\Operations.txt as expected.

Executing an external executable in a working directory containing spaces in Java?

I have a specific need to unrar files found in different subdirectories during execution of my program on Os x. I do this by calling the freeware command line tool unrar, which works very well.
However, unrar will always unrar files in the current working directory, which means that I have to specify a working directory for the executed process or get every unpacked file in my .jar home folder.
This is easy enough to do using either the processBuilder.directory(dir) or runTime.getRuntime().exec(args,null,dir) for example where dir is a File.
This works excellent but not when the working directory contains a space. As a short example:
File dir=new File("/Users/chargedPeptide/rar 2");
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar", "2/weather.rar"};
Process pr = Runtime.getRuntime().exec(cmd,null,dir);
int exitValue=pr.waitFor();
Will not work, while using: Process pr = Runtime.getRuntime().exec(cmd); instead will launch the command successfully but leave me with all of the files in the jars working directory.
Using processbuilder instead and using processbuilder.directory(dir); to set the directory
exits with the message:
Exception: Cannot run program "/Users/chargedPeptide/rar/unrar" (in directory "/Users/chargedPeptide/rar 2"): error=2, No such file or directory
Help? How do I handle the spaces? I've tried adding backslashes before the spaces to make them literal no help since the File object treats them like actual part of the path.
Edit: To make the whole thing a bit more clear:
1. I have a separate method that feeds the execute method a command and a directory to processbuilder, all directories are found by the previous method and exist. This works except when the dir contains a space.
2.I need to set the working dir or the command will execute in the wrong place.
3.Parsing the file object by:
dir=new File(dir.tostring.replace(" ","\ ");
to put a backslash in front of all spaces does not work since the java File object then looks for a path containing actual backslashes. No luck.
4.Using rt.exec instead of processbuilder dosen't help either.
Any ideas most welcome.
How about:
dir.mkdirs();
before launching the process.
This creates the missing directory.
Edit:
This looks strange.
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar", "2/weather.rar"};
If this was a shell you'd write:
unrar e -o+ "/Users/chargedPeptide/rar 2/weather.rar"
You actually have to put the .rar file in quotes, since otherwise it will be interpreted as 2 arguments to the process.
The way you've split 'cmd' will do exactly that, break the rar argument in two. Try:
String[] cmd = { "/Users/chargedPeptide/rar/unrar", "e", "-o+","/Users/chargedPeptide/rar 2/weather.rar"};
Not sure if it will work, but can you try putting a / at the end of the path.
i.e.,
File dir=new File("/Users/chargedPeptide/rar 2/");

Categories