Calling fortran90 exe program from java is not executing - java

I am trying to call Fortran 90 program from java program,
My Fortran program is as follows:
!sum.for
program Numbers_sum
implicit none
! -----------------------------------------------Declare
REAL :: a,b,sum
! -----------------------------------------------Input
print*,"Enter first number..."
read*, a
print*,"Enter second number ..."
read*, b
! -----------------------------------------------Compute
sum = a+b
! -----------------------------------------------Output
print*,"Sum =", sum
end
Which is working on Fortran compiler. And finally I got an exe file which will execute and give fortran result. I am trying to call it from my java program,
My java program as follows:
import java.io.File;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Sum {
public static void main(String []args) {
String filePath = "sum.exe";
if (new File(filePath).exists()) {
try {
ProcessBuilder pb = new ProcessBuilder(filePath);
pb.redirectError();
Process p = pb.start();
InputStream is = p.getInputStream();
int value = -1;
while ((value = is.read()) != -1) {
System.out.print((char) value);
}
int exitCode = p.waitFor();
System.out.println(filePath + " exited with " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.err.println(filePath + " does not exist");
}
}
}
But it is not working.
I am calling the java from my command prompt as follows:
But cursor blinking only. It is not working.
I did cntrl+c to escape from the java command prompt . That case I gott like the following:
Why it is not working. Please help me. How I could read that exe from my java program correctly. Any help will be appreciated!!

Seems that you need to redirect streams here--so input stream of fortran execution process would be redirected to System.in and output stream to System.out. Just put the following lines:
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
before pb.start().

Related

How to execute bash commands in Java (Raspberry pi)

I dont know why, but I can only execute a very small pallet of commands on my Raspberry 3B from code (I cane even execute echo). For some reason, 99% of the commands that you would normally be able to do in the terminal itself, you cant do from code.
Example: I execute this java code:
Runtime.getRuntime().exec("echo hi");
And I get this:
`java.io.IOException: Cannot run program "echo hi": error=2, No such file or directory
Is there a PATH configuration that I dont have access to in java code? why cant I execute any commands to the raspberry pi from code?
I've written some example that uses the exec() call. There are other methods to start processes from within Java (ProcessBuilder is the keyword here), but this example is relatively easy to understand:
import java.util.*;
import java.io.*;
import java.text.*;
public class X {
public static void main(String argv[])
{
String args[] = { "/bin/bash", "-c", "uptime" };
try {
Process p = Runtime.getRuntime().exec(args);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = in.readLine();
while (line != null) {
System.out.println("Found: " + line);
line = in.readLine();
}
} catch (Exception e) {
System.err.println("Some error occured : " + e.toString());
}
}
}
Basically the program executes the command line /bin/bash -c uptime; just an uptime would have done the same, but I wanted to show how to work with command line arguments for the program to start.

How make code to simulate the command < file.txt

I'm developing java code that needs to simulate the following:
my_command < file.txt
I tested writing to STDIN but it doesn't seem to be the solution.
Has someone already developed it?
Note, in the below code,
source is an instance of java.io.File
String commandLine = "myCommand";
Process process = Runtime.getRuntime().exec(commandLine);
new Thread(() -> {
try (BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
Scanner scanner = new Scanner(source)
){
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
stdin.write(line);
System.out.print(line);
}
stdin.flush();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
int ret = process.waitFor();
FYI my command is mysql
You should use class ProcessBuilder (rather than class Runtime).
I don't know what your my_command is, so the below code uses cleartool.
First I create the text file containing the cleartool subcommands that I wish to execute.
hostinfo
exit
(Note the empty last line of the file.)
I named this file exits_ct.txt
Now the java code that will run cleartool command, then enter the subcommands from the text file and print the command output to standard output.
import java.io.File;
import java.io.IOException;
public class PrcBldTs {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("cleartool");
pb.redirectInput(new File("exits_ct.txt"));
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
Process proc = pb.start(); // throws java.io.IOException
int result = proc.waitFor(); // throws java.lang.InterruptedException
System.out.println("result: " + result);
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
When I run the above code, I get the following output:
MY_COMP: ClearCase 9.0.0.0 (Windows NT 6.2 (build 9200) Pentium)
result: 0

execute sql loader as administrator from java app

My requirement is to load a script using sql loader from within my java app. For this purpose, I've been using the following script
D:\oracle\product\10.2.0\db_1\BIN\SQLLDR.EXE userid=myDBUserID/myDBPswrd data=C:\Users\myUserName\Desktop\sql_ldr_files\1\table_export_DATA.ldr control=C:\Users\myUserName\Desktop\sql_ldr_files\1\table_export_DATA.ctl log=C:\Users\myUserName\Desktop\sql_ldr_files\1\logitit.log discard=C:\Users\myUserName\Desktop\sql_ldr_files\1\discard.txt bad=C:\Users\myUserName\Desktop\sql_ldr_files\1\bad.txt
But while trying to run it first on cmd prompt, i realized that the command won't run if I do not run it, on cmd prompt which is launched by "Run as Administrator".
Once the cmd was launched by "Run as Administrator", the command ran successfully, the script executed and the table got populated properly.
Now my task was to use the same code, but run it from within a java code. For this, I've used the following java code,
import java.io.FileWriter.*;
import java.io.BufferedWriter.*;
import java.io.BufferedReader.*;
import java.io.InputStreamReader.*;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunSqlLrdFromJava
{
public static void main(String s[])
{
try{
Runtime rt = Runtime.getRuntime();
String sqlLoaderPath = "D:\\oracle\\product\\10.2.0\\db_1\\BIN\\";
String runAsCmd="runas /user:myPCName\\administrator ";
String cmd = runAsCmd + "\""+sqlLoaderPath + "SQLLDR.EXE userid=myDBUserID/myDBPswrd "
+ " data=C:\\Users\\myUserName\\Desktop\\sql_ldr_files\\1\\table_export_DATA.ldr"
+ " control=C:\\Users\\myUserName\\Desktop\\sql_ldr_files\\1\\table_export_DATA.ctl"
+ " log=C:\\Users\\myUserName\\Desktop\\sql_ldr_files\\1\\logitit.log"
+ " discard=C:\\Users\\myUserName\\Desktop\\sql_ldr_files\\1\\discard.txt"
+ " bad=C:\\Users\\myUserName\\Desktop\\sql_ldr_files\\1\\bad.txt " + "\"";
try{
FileWriter file = new FileWriter("ExceptionInSqlldr.txt");
BufferedWriter bf = new BufferedWriter(file);
bf.write("SQLLDR COMMAND:\n" +cmd +"---------------------------------\n\n\n");
Process proc = rt.exec(cmd);
int exitVal = proc.waitFor();
BufferedReader br = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
String line;
System.out.println("\n------------------exitVal:"+exitVal+"------------------\n\n");
bf.write("SQLLDR COMMAND:\n" +cmd +"---------------------------------\n\n\n");
if(br!=null && exitVal!=0)
{ while((line = br.readLine()) != null)
{
bf.write("\n"+ line +"\n");
System.out.println("Read from error stream: \"" + line + "\"");
}
}
proc.destroy();
bf.close();
}
catch(Exception e)
{
e.printStackTrace();
//System.out.println(e.getMessage());
}
}
catch(Exception e)
{
e.printStackTrace();
//System.out.println(e.getMessage());
}
}
}
But this time, it won't run.
My problem is, when we use "run as" to run the process as administrator on command prompt, it prompts for a password. Thus when I'm using the same "run as" command from within a java code, I can't provide the response to that prompt [as it seems at the least].
Is there a wayout, where I can run the command as an administrator from within my java code by passing the password for administrator inside the command only, so that my java code becomes successfull in running it?
Please advice as I didn't ever do it before.
Warm regards.

Not able to see the Perl output executing from Java class

I am using a Java class to execute a Perl script on a Linux box. The .class is being created successfully.
But when I execute the class, it says exit code successful as sop, but I'm not able to see the Perl output or the execution of the script. If I execute the Perl directly, it works fine...
This is the Perl script:
#!/usr/local/bin/perl
print ("Enter the distance to be converted:\n");
$originaldist = <STDIN>;
chop ($originaldist);
$miles = $originaldist * 0.6214;
$kilometers = $originaldist * 1.609;
print ($originaldist, " kilometers = ", $miles, " miles\n");
And this is my Java class to call the script:
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class test {
public static void main(String[] args) throws IOException {
String[] aCmdArgs = { "perl", "-e"
, "pl newprg.pl" };
Runtime oRuntime = Runtime.getRuntime();
Process oProcess = null;
try {
oProcess = oRuntime.exec(aCmdArgs);
oProcess.waitFor();
} catch (Exception e) {
System.out.println("error executing " + aCmdArgs[0]);
}
/* dump output stream */
BufferedReader is = new BufferedReader
( new InputStreamReader(oProcess.getInputStream()));
String sLine;
while ((sLine = is.readLine()) != null) {
System.out.println(sLine);
}
System.out.flush();
/* print final result of process */
System.err.println("Exit status=" + oProcess.exitValue());
return;
}
}
Two issues:
perl -e pl newprg.pl will not actually execute your program from the command line, as it will fail to parse the given (non) expression. You probably meant to use perl newprg.pl
Your program requires input, which you will need to pipe in using the output stream of the process
For example:
try {
oProcess = oRuntime.exec(aCmdArgs);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
oProcess.getOutputStream()));
writer.println(200);
writer.close();
oProcess.waitFor();
} catch (Exception e) {
System.out.println("error executing " + aCmdArgs[0]);
}

Executing command in cmd and showing output in jTextArea of swing GUI application

I am developing a swing gui application in which i want to execute some cmd commands and show their output in a jTextArea and i also want to enter values asked during program execution in a jTextField. Plase provide some code which can help me to achive my goal.
This code should get you started with executing cmd commands from java and capturing their output:
import java.io.InputStream;
public class CmdProxy {
public static void main(String [] args) {
try {
Process proc = Runtime.getRuntime().exec("cmd /C \"dir \\ \"");
InputStream is = proc.getInputStream();
// NOTE: this is not the most elegant way to extract content from the
// input stream
int i = -1;
StringBuilder buf = new StringBuilder();
while ((i = is.read()) != -1) {
buf.append((char)i);
}
proc.waitFor();
System.out.println(buf.toString());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Try it in your sandbox and see what happens. Note that the /C option ensures the cmd process terminates after it is done handling the command arguments we passed (in this case, "dir \ "). In your case you want to exec "cmd /C \"" + whateverUserSpecified + "\"". Obviously, I'm assuming you're programming in/for a Window's environment. I'll let you or someone else figure out the GUI code.

Categories

Resources