This question already has answers here:
How do I run a batch file from my Java Application?
(12 answers)
Closed 8 years ago.
Lets suppose I have a listener for a Button
public class Visualizer1 implements ActionListener {
public void actionPerformed(ActionEvent a) {
try {
Runtime rt2 = Runtime.getRuntime();
Process p = rt2.exec("visualizer/vis1.exe");
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream();
InputStream err = p.getErrorStream();
p.destroy();
} catch (Exception exc) {/* handle exception */
}
the "vis1.exe" will execute without any problem and it will open up
but if I have an application with a ".bat" extension like if it was(vis1.bat), it won't open up.
Note: .bat extension is an executable file
Try this..
Runtime.getRuntime().exec("cmd /c start vis1.bat");
a .bat isnt an executable file.
"A .BAT (short for "batch") file is a plain text file that contains a series of Windows commands. An .EXE (short for "executable") file is a binary file that contains much more complex executable binary code."
http://www.fileinfo.com/help/bat_vs_exe_files
Have you gone through previous threads on same issue on stackoverflow.com?
Have a look at followings:
How do I run a batch file from my Java Application?
Run batch file from Java code
How to execute a batch file from java?
Run a batch file with java program
Related
This is not about creating a batch file or executing a batch file from java but creating a binary from them.
I am not very sure about Linux shell scripts but is know that for Windows Batch scripts there are some programs like Batch to Exe Converter. But i want to do it programmatically.
Suppose I read the contents of a batch file from a file :
public static String loadFile(String filepath) {
List<String> lines = Collections.emptyList();
try
{
lines =
Files.readAllLines(Paths.get(filepath), StandardCharsets.UTF_8);
}
catch (IOException e)
{
e.printStackTrace();
}
String s = "";
for(String line:lines){
s += line + "\n"
}
return s;
}
Now i want to convert it to an exe.
Purpose
My main purpose is to create small executables from those scripts for some small automations which will be used instead of the scripts themselves.
For example:-
I have a setup.bat file.
I have my program to automatically generate the batch every time I make any changes(add files) now i also want to have executables along with the scripts.
I also a curious whether a similar thing is possible for Linux shell scripts(creating executables).
Moreover i this is not possible through Java directly can we some how do it using JNI?
i have written a python script to goto a website and scrape some text off the website and save that text into a text file on my computer
from selenium import webdriver
import os
chrome_path = r"C:\tf_alert\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.minuteinbox.com/")
email = driver.find_element_by_xpath("""/html/body/div[2]/div[3]/div[1]/div[3]/div/span""").text
strEmail = str(email)
mailMan = open("10MAIL.txt", "a")
mailMan.write(strEmail)
mailMan.close()
os.system("taskkill /im py.exe")
when i run the script from where it is located on my computer all works fine and text is properly written to text file on my computer
but when i try to integrate the python script into a java program (code below), the text scraped off of the website does not get written to text file
public void SimpleTest() throws InterruptedException, IOException {
Desktop desktop01 = Desktop.getDesktop();
File file01 = new File("C:\\tf_alert\\other python projects\\mailMan.py");
if (file01.exists()) {
desktop01.open(file01);
}
Thread.sleep(20000);
StringBuilder contentBuilder01 = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get("C:\\tf_alert\\other python projects\\10MAIL.txt"), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder01.append(s).append(""));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(contentBuilder01);
PrintWriter pw = new PrintWriter("C:\\tf_alert\\other python projects\\10MAIL.txt");
pw.close();
}
the purpose of the java program above is to activate the python script to scrape text off a website, then get the text written from the python script from the file on my computer, print the text to console, and then clear the text file so that all is ready for next execution
the problem is occuring during the writing of text mailMan.write(strEmail) in python code because when java prints the text from the text file it prints a blank ""
i suppose there is interference between java and python
can anyone help out?
You are not executing the python script.
Running a .py file from Java should help you.
Another source: Three ways to run Python programs from Java
to fix this problem i created a windows batch file that changes directory to where the python file is located and starts that file
cd C:\your-directory
start yourscript.py
This question already has answers here:
Open a text file in the default text editor... via Java?
(3 answers)
Closed 4 years ago.
I want to open a txt file using java
For running .exe I use this:
try {
Runtime.getRuntime().exec("c:\\windows\\notepad.exe");
} catch (Exception e) {
e.printStackTrace();
}
I have tried to run .txt file and it doesn't work. I get IOException with this message:
CreateProcess error=193, %1 is not a valid Win32 application
How I can run a .txt using java?
You cannot "run" a .txt file. Because a text file simply respresents a set of characters with a certain encoding. Whereas on the other hand an exe is a file containing compiled code. That is information specifically for the machine to understand.
If, like in your example above, you want to open a textfile in Notepad, you have a few options. One goes as follows
try {
Runtime.getRuntime().exec(new String[] { "c:\\windows\\notepad.exe", "C:\\path\\to\\the.txt" });
} catch (Exception e) {
e.printStackTrace();
}
Notepad is already set in your PATH environment variable, you miss only the paremeter: the file to be opened:
Runtime.getRuntime().exec("start notepad 'PATH/TO/file.txt'");
FYI notepad argument list:
/A <filename> open file as ansi
/W <filename> open file as unicode
/P <filename> print filename
/PT <filename> <printername> <driverdll> <port> print filename to designated printer
This question already has answers here:
Running a .exe file using Java
(4 answers)
Closed 9 years ago.
Actually I am working Wolfram Mathematica,we don't have any functions for running external programs, so I want to do this App using Java technology.
In my organization, C developing team, developed one Application and given to us in a .exe format.Know I want to run that .exe file from Java.
I have a .exe name as ThMapInfratab1-2.exe under C:/Users/Infratab Bangalore/Desktop/Rod's directory.
once we run the .exe file, automatically I takes .txt file as a input name as TherInput.txt from the same directory (C:/Users/Infratab Bangalore/Desktop/Rod's)
For my conformation, I run the ThMapInfratab1-2.exe file manually using command prompt in the following way.it's working great.
C:\Users\Infratab Bangalore\Desktop\Rod's>ThMapInfratab1-2.exe
Finally .exe file exports t .txt files as a output into same directory(C:/Users/Infratab Bangalore/Desktop/Rod's).
These same thing, I want to do using Java.can you explain with my directories.
For this, I wrote the following code but it's not working.
import java.io.IOException;
public class ProcessBuilderSample {
public static void main(String args[]) throws IOException {
Process process = new ProcessBuilder(
"C:\\Users\\Infratab bangalore\\Desktop\\Rod's\\ThMapInfratab1-2.exe")
.start();
}
}
If anyone knows,suggest me.
Thanks.
.
You need to execute exec() method of Runtime that returns Process instance or use ProcessBuilder class methods.
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("C:\\Users\\Infratab Bangalore\\Desktop\\Rod's\\ThMapInfratab1-2.exe");
You can use ProcessBuilder as
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();
assert pb.redirectInput() == Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;
You can do it like this:
Process process=Runtime.getRuntime().exec("C:\\Users\\Infratab Bangalore\\Desktop\\Rod's\\ThMapInfratab1-2.exe");
Process process=Runtime.getRuntime().exec("C:\Users\Infratab Bangalore\Desktop\Rod's>ThMapInfratab1-2.exe");
I am trying to add a text file to a zip archive through a Java program on Linux. The program spawns a process (using java.lang.Process) to execute the commandline "zip -j .zip .txt", reads the output and error streams of the spawned process and waits for the process to complete using waitFor(). Though the program seems to run fine (spawned process exits with exit code 0, indicating that the zip commandline was executed successfully) and the output read from output and error streams do not indicate any errors, at the end of the program the zip archive doesn't always contain the file supposed to have been added. This problem doesn't happen consistently though (even with the same existing-archive and file-to-add) - once in a while (perhaps once in 4 attempts) the zip is found to have been updated correctly. Strangely, the problem doesn't occur at all when the program is run through Eclipse debugger mode. Any pointers on why this problem occurs and how it can be addressed would be helpful. Thanks!
Below is the code snippet. The program calls addFileToZip(File, File, String):
public static void addFileToZip(final File zipFile, final File fileToBeAdded,
final String fileNameToBeAddedAs) throws Exception {
File tempDir = createTempDir();
File fileToBeAddedAs = new File(tempDir, fileNameToBeAddedAs);
try {
FileUtils.copyFile(fileToBeAdded, fileToBeAddedAs);
addFileToZip(zipFile, fileToBeAddedAs);
} finally {
deleteFile(fileToBeAddedAs);
deleteFile(tempDir);
}
}
public static void addFileToZip(final File zipFile, final File fileToBeAdded) throws Exception {
final String[] command = {"zip", "-j", zipFile.getAbsolutePath(), fileToBeAdded.getAbsolutePath()};
ProcessBuilder procBuilder = new ProcessBuilder(command);
Process proc = procBuilder.start();
int exitCode = proc.waitFor();
/*
* Code to read output/error streams of proc and log/print them
*/
if (exitCode != 0) {
throw new Exception("Unable to add file, error: " + errMsg);
}
}
Make sure no other process has the zip file locked for write, or the file being added locked for read. If you're generating the file to be added, make sure the stream is flushed and closed before spawning the zip utility.
I am trying to add a text file to a zip archive through a Java program on Linux.
Use the java.util.zip API, which:
Provides classes for reading and writing the standard ZIP and GZIP file formats.
If you intend to stick with using a Process to do this, be sure to implement all the suggestions of When Runtime.exec() won't.