Unable to refer the path when invoke the Jar file from R - java

I am new one for R language and question is related to R language.
I created simple Java program which is used to check the file is available or not.
String sampleCSVFileLocation = "source/SampleCSVFile.csv";
File file = new File(sampleCSVFileLocation);
if (file.exists())
{
System.out.println(sampleCSVFileLocation + " is available");
}
else
{
System.out.println(sampleCSVFileLocation + " is not available");
}
I convert this program as Test.jar and stored into this location C:\Demo.
and I put the SampleCSVFile into the same location.
This is my file structure:
C:/Demo/Test.jar
C:/Demo/source/SampleCSVFile.csv
I run this code from command line and am getting the correct output and it goes to IF block.
C:\Demo>java –jar Test.jar
source/SampleCSVFile.csv is available
My Problem is:
I run the same jar from R language. I am getting wrong output. It goes to else block.
>system(“java –jar C:/Demo/Test.jar”)
source/SampleCSVFile.csv is not available
It unable to refer the source folder path.
I don’t want change the java code.
How to resolve this issue.
Help me.
Thanks in advance.

Try to set working directory, before exec jar.
setwd("C:/Demo")
More information here -http://stat.ethz.ch/R-manual/R-patched/library/base/html/getwd.html

Related

How to Write Output Files from a JAR Program to Directory Outside the JAR?

tl;dr I'm more used to writing command-line scripts that can just output based on the current working directory, so I'm unsure what directory to use for output files in a program that will be launched from a JAR.
Program Description:
My program builds an HTML file from data given to it from the rest of the program, and then is supposed to write it to a file that we'll call "Output.html" for simplicity.
Relevant Code:
public void outputHTML()
{
String output = buildHTML();
// Expanded to explain my confusion better
String fileDirectory = ""; // ???
String fileName = "Output.html";
String fullPath = fileDirectory + "\\" + fileName;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fullPath)))
{
writer.write(output);
writer.close();
} catch (IOException e)
{
System.out.println("File not found.");
e.printStackTrace();
}
}
Problem
I don't know what to put the file directory as. Usually I run my programs from the command line and use ".\\Output.txt" as my output path, but I don't know where to put it if it's being run from a JAR.
The desired file structure is as follows:
Encompassing Folder
Program.jar
output
Output.html
Or alternatively (not sure if this makes it easier to understand or harder):
main\
main\Program.jar
main\output\
main\output\Output.html
Everything I can find on SE only relates to reading files that are both immutable and internal, but I'm trying to output a non-static file to a location outside of my jar.
Can anyone help with this? Thanks!
Misc Details
I'm using Eclipse without Gradle currently, because I don't know what Gradle is and new things are scary. If this particular problem would be easier to solve with Gradle, let me know and I'll look up more about it.
EDIT:
Added syntax highlighting to code block.
Formatted everything a bit better
Changed title to be more descriptive
You can use an absolute path: e.g. fileDirectory = "\\project\\test\\main\\output";
using normal slash should also work even on Windows ("/project/test/main/output")
Or use a relative path - this will start from the current working directory (user directory), the one where the JVM was started in - e.g. fileDirectory = "main\\output";

Execute shell command from java in specific folder

I have a C code which I have compiled and added to path in order to be able to execute it form anywhere (I've double checked that I can do that)
Now I want to do a GUI to work with it in an easier way. I ask the user to input a file and an output directory.
In a click button I put the code to execute the command from the GUI:
String command = "myprogram -e " + file;
new ExecuteShellInstruction().main(command,jTextOutputDirectory.getText());
I execute the code in other class:
p = Runtime.getRuntime().exec(command, null, new File(directory));
But I always get this error:
java.io.IOException: Cannot run program "myprogram" (in directory "/Users/user_name/Documents/folder/example"): error=2, No such file or directory
I've checked that if I write exactly the same from the same folder there is no problem.
Any idea of what I'm doing worng?, If obtained this way of doing it from a question which was marked as correct, maybe I'm missing something, but I've already been 1 hour trying things and nothing seems to work.
Thank you!
Finally I found a solution.
It seems like you have to tell that your application can be executed by adding "./" at the beginning. Something like this:
String command = "./myprogram -e " + file;

{Java} File exists but still showing FileNotFoundException Error

I need to read a .txt file of integers into a 2d array but when I try to read in the file I get a runetime error saying that the specified file cannot be found. This is the first time I've tried to read in a file so I just need direction on how to do it but I couldn't find an answer this basic.
I have the file of integers named "num1.txt" saved in the same folder as as my java file, so I'm wondering if I don't understand how eclipse and java decide where the file is.
public static void main(String[] args) throws FileNotFoundException
{
int i;
int j;
i=0;
j=0;
int connect4Array[][] = new int[6][7];
Scanner readFile = new Scanner(new File("num1.txt"));
while(readFile.hasNextInt())
{
for(i=0;i<connect4Array.length;i++)
{
connect4Array[i++][j]=readFile.nextInt();
for(j=0;j<connect4Array[j].length;j++)
{
connect4Array[i][j++]=readFile.nextInt();
}
}
}
First of all, it is NOT a compilation error. It is a runtime error. You need to learn the difference ... and to say the right thing, or else people won't understand what you are talking about.
I have the file of integers named "num1.txt" saved in the same folder as as my java file.
The problem is that you are trying to access the file in the running application's current directory ... but the current directory is not the place that you think / hope it is.
So where is the application's current directory? It depends on how you ran the application!
If you run the java app from a shell, then the current directory will default to the shell's current directory.
You can change it by cd-ing before you run java ... and I think you can also specify it using -Duser.dir=<pathname>.
If you run the java app from Eclipse, then the current directory will default to the project directory. That is probably different to the directory containing the source code.
You can specify a different current directory in the Eclipse settings for your application's launcher.
Alternatively, use an absolute path for the file, or put it into your application's JAR file and read it as a "resource".
move the file to where the src folder located.
because the default is project directory in your workspace.
you can use getProperty to check current directory.
String CurrentDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + CurrentDir);

Java: find current working JAR

I know that the system property "user.dir" returns the current working directory; the directory containing that file that is currently running.
I am wondering, how would I be able to go one step farther? I need to find the current working file. I am writing a little app that is kind of like an auto-updater, and I need to know the file that needs to be updated. For example, if I run a file from C:/test.jar I want to actually know, in code, that the current location of the file that is running is C:/test.jar so that I can write (new) data to it.
I've tried an approach like this:
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("Test.class"));
However, it prints out:
3/5/12 7:50:16.914 PM [0x0-0x31031].com.apple.JarLauncher: rsrc:Test.class
(I am running this on a Mac - I got that line from the Console).
Any help is greatly appreciated. Thanks!
With credits to Fab in the following post:
Jar path+name from currently running jar
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
This will print the current file's path.
File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
System.out.println(f.getPath());

File.listFiles() returns files in current working directory in Java [duplicate]

I was just reading some java book and making some small programs for practice, I created a small code to get information about the path I entered, and the code is:
String path = JOptionPane.showInputDialog("Enter Path to analyze");
File file = new File(path);
if (file.exists())
{
String result = "";
if (file.isDirectory())
{
result += "Path is directory\n ";
String [] resList = file.list();
for (String s : resList)
{
result += s + ", ";
}
}
if (file.isFile())
{
result += "Path is a file\n";
}
JOptionPane.showMessageDialog(null, result);
Now in the input dialogue, when I enter C:, the result is build, build.xml, manifest.mf, nbproject, src, but when I enter C:/, it shows the complete list of directories and files in C.
And strangely it does not happen with the D drive and other drives (i.e. the result is same for D:/ and D:), what is happening please explain?
Update
Same happens in WPF using C#!
C: means "whatever directory is currently selected on drive C:". In your case, it's probably the directory that your application is running from.
D: is the same as D:/ in your case because the root directory is the current working directory in D:.
This is not really a java question, but a windows/dos question.
The explanation comes down to the old dos command for switching drives.
Typing a drive letter followed by a colon is a command to change drives in dos, therefore the 'command' C: does nothing since your working dir is already on the C drive. The 'directory' returned by the native interface to the JRE is the same as if you used the path "", ie your working directory.
On the other hand, add a slash and it is a proper path, to the root of your C drive, therefore your JRE is given this directory by the native interface.
If you go to a dos command (windows>run>cmd) and type in C: you will see that it accepts the command but does not change directory, unless of course you are currently on a different drive at the time.
hope that helps.

Categories

Resources