Calling bash script from Java - java

I have this MCVE for an Java class calling a bash script:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Test
{
static BufferedReader in;
public static void main(String[] args) throws Exception
{
String[] cmd = new String[]{"/bin/sh", "/usr/myapp/myscript.sh", "parameter1"};
Process pr = Runtime.getRuntime().exec(cmd);
in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
}
}
When I have the compiled .class file in the same directory as myscript.sh, it works just fine.
As soon as I move the .class file to another folder, it doesn't execute the script anymore, although I am still using the absolute path to the script.
I tested this with JDK 1.8 on a BeagleboneBlack running Angstrom if this information is good for something.
How can I run the script, although it is in a different location?

Using the getErrorStream hint by Samuel really helped.
It was clear, that some sub-scripts that were in the same folder as the original shell script were not found.
The solution was as easy as using absolute paths to sub-scripts as well since the working directory is not the one of the called script but the one of the calling application (in my case the Java App)

Related

Trying to compile and run c++ code with java code

I was trying to compile and run a c++ program from a java program, I made a .bat file having compilation and execution command, The code for making .bat file works fine, but code to open the .bat file doesn't work. It says "g++ is not recognized as an internal/external command", but if I open .bat file manually, it works fine. please help me with the code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Batch
{
FileOutputStream fos;
DataOutputStream dos;
public Batch()
{
}
public void createBat() throws Exception
{
File file=new File("M:\\AV\\compile_Execute.bat");
fos=new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeBytes("#echo off");
dos.writeBytes("\n");
dos.writeBytes("g++ main.cpp -o main.exe -lmingw32 -lSDL2main -lSDL2 & main.exe");
fos.close();
}
public void executeBat() throws Exception
{
String[] command = {"cmd.exe", "/C", "Start", "M:\\AV\\compile_execute.bat"};
Process p = Runtime.getRuntime().exec(command);
}
}
What happens here is that you messed up with the path, because the file is located in another drive, you cannot just use the path or go back a folder using ".."
Firstly, go to the biggest directory
cd "C:\"
Then, change drive
M:
Note that to change directoy you must be in the drive biggest folder and that to change drives, you must use the format letter:
These two steps can be simplified to cd D:
Next:
cd "M:\\AV\\"
Finally:
compile_execute.bat
Merging it, I would use this instead of just a path: cd /D M:\\AV\\ compile_execute.bat
I suggest reading about MS-DOS.
Thanks for the comment related to not being able to change directory to a file.

File not found exception error in Java

I'm trying to read a file but I can't seem to make it work. It shows an error: "File not found exception". The system cannot find the file specified. I enclosed the code below. Can anyone solve this issue?
package trailfiledemo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*
* #author VIGNESH
*/
public class Trailfiledemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
FileReader fr=new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Check if your file exists within the designated file path as it needs to match. Another possibility that Joik mentioned above, is your compiler might not have permission to access the file within the path given. You could try an alternative file path if that is the case.
FileNotFound exception has wrong name. It may appear not only in case the file is absent, so there is an ambiguity.
There are three cases where a FileNotFoundException may be thrown:
1.The file does not exist.
2.The file is actually a directory.
3.The file cannot be opened. It may have no read access in your OS.
You need to check all 3 fail cases to be sure about the root of the issue. Documentation page contains some details:
https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
I implemented your code and only changed your username to mine and it compiled like a charm. Read everything in the file and ended succesfully.
Try:
Click on Run > Clean and Build Project maybe it didn't take one of your changes.
Other things you might want to try:
use a buffered reader:
try (BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt"))) {
String line;
while ((line = br.readLine()) != null)
System.out.print(line + "\n");
}
Or you could move the file into the same folder as the code and use this path '"src\stackoverflow\hellodata.txt"' stackoverflow => your packageĀ“s name

Can't Get Java Program to List Files In A Specified Directory

I am trying to write a program (for school homework) that will take a command-line argument to specify a directory, and for the time being, just print out the files in the directory. I have literally been looking at various answers and trying things out for hours now, and just have no idea what to do. Below, you will find my current code. when I open a CMD, and type java DirectoryFiles c:\ .
I get Error, could not find or load main class DirectoryFiles. I just used c:\ to see if I could get any directory to print out.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class DirectoryFiles
{
/**
* Gets command line argument for directory to be used in program.
*
* #param args
*/
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
String path = args[0];
File dir = new File(path);
FileInputStream fis = new FileInputStream(dir);
if ((dir).isDirectory())
{
File[] files = dir.listFiles();
System.out.println(files);
}
}
}
Most likely you have only the source file (you didn't compile it).
Remember that:
Java is not an interpreter of a source file.
java command attempts to run an existing java class.
So you must start from compiling the source code into a Java class.
Then you can run it with java command.

Why can my library not access its resources?

I have a class that reads a file:
package classlibrary;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class ReadingResource {
public static String readResource() throws IOException {
URL resource = ClassLoader.getSystemClassLoader().getResource("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new FileReader(resource.getPath()));
return br.readLine();
}
}
The resource file is in the same directory where this class is.
I made a library out of this class and the file.
Now I want to use it in the other class:
package uritesting;
import classlibrary.ReadingResource;
import java.io.IOException;
public class URITesting {
public static void main(String[] args) throws IOException {
System.out.println(ReadingResource.readResource());
}
}
When I make a .jar file out of this class, set the class as the main class, add the .jar from above and execute it as "java -jar URITesting.jar" I get a FileNotFoundException, saying the class ReadingResource can not find the specified file. It is funny because the path that is specified in the exception message is actually the correct path to the file.
You can find the files here.
EDIT:
I developed the project in NetBeans. When I run it there, it works fine. The classpath is different in that case. It contains both resources of the URITestingProject and ReadingResource.
However, when I run it as a standalone JAR, the classpath contains URITestingProject only. What is strange to me is that it doesn't complain about not finding the class ReadingResource. It means that it is loaded, although it is not in the classpath :/
The problem is resource.getPath(). It's not possible to calculate a path ,valid for a file reader, inside a jar file, on another server and so on. However you can get the data through a stream instead:
InputStream data = ClassLoader.getSystemClassLoader().getResourceAsStream("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(data, "utf-8"));
As a side note: When reading with reader it's a good idea to specify the encoding:

Python ImportError when calling Python script from Java

First off, there is a similar question here that wasn't ever really resolved.
I have a Python script that I want to execute from within my Java code. When I run the Python script on its own, it works properly. When I try to execute it from a Java process, I get an ImportError:
Traceback (most recent call last):
File "address_to_geocode.py", line 3, in <module>
from omgeo import Geocoder
ImportError: No module named omgeo
Per a suggestion from the linked question, I appended a direct path to the module in my Python import section to make sure the interpreter knows where to look, yet it still won't work:
import sys, os
sys.path.append('/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/omgeo')
from omgeo import Geocoder
My next move was to call the python script from a bash script (which again, works on its own), but when I call the bash script from Java, the same error persists. The issue, therefore seems to be on Java's end. Here is my java code:
Process p = runner.exec("python address_to_geocode.py");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String stdReader = null;
//Read output of command:
while((stdReader = stdInput.readLine())!=null) {
System.out.println(stdReader);
}
//Read any command errors:
while((stdReader = stdError.readLine())!=null) {
System.out.println(stdReader);
}
p.waitFor();
Is there anything wrong with my Java code or is this a bug? I appreciate any pointers.
I solved it. It looks like ProcessBuilder requires the full path not only to the python file itself, but to python:
ProcessBuilder("/Library/Frameworks/Python.framework/Versions/2.7/bin/python",absolute_file_path);
This solves the issue.
Find your python bin location
$ cat ~/.bash_profile
Java code
ProcessBuilder pb = new ProcessBuilder("/Users/micklin/anaconda2/bin/python","sentiment.py",done.toString());
code above is put in TweetFeeder.java so that .py file can be put under the project root

Categories