Cannot access and run batch file commands using java class - java

I have created a java class to execute a batch file that is in my desktop so that the commands in the batch file will be executed too. The problem is that, i keep getting the error:
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
I have checked the .bat name and the directory. It is correct. When i type cmd /c start C:/Users/attsuap1/Desktop, windows explorer opens the desktop tab. However when i type cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat, it gives the error. My DraftBatchFile.bat is in my desktop.
Here are my java codes:
public class OpenDraftBatchFile{
public OpenDraftBatchFile() {
super();
}
/**Main Method
* #param args
*/
public static void main(String[] args) {
//Get Runtime object
Runtime runtime = Runtime.getRuntime();
try {
//Pass string in this format to open Batch file
runtime.exec("cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat");
} catch (IOException e) {
System.out.println(e);
}
}
Why is it that the batch file cannot be executed even if the directory is correct? Someone please help me. Thank you so much.
These are the codes in DraftBatchFile.bat
#echo off
echo.>"Desktop:\testing\draft.txt"
#echo Writing text to draft.txt> Desktop:\testing\draft.txt
When i execute the DraftBatchFile.bat by running the java class, i want a draft.txt file to be created in a testing folder that i have created (in desktop).

there is no such thing as desktop:\
Instead try something like this.
#echo off
echo . %userprofile%\Desktop\testing\dblank.txt
#echo Writing text to draft.txt > %userprofile%\Desktop\testing\dblank.txt

You just need to change a directory and create new subdirectory if it not exist. My offer is change .bat file like this:
#echo off
if not exist "%userprofile%\Desktop\testing" mkdir "%userprofile%\Desktop\testing"
echo.>"%userprofile%\Desktop\draft.txt"
#echo Writing text to draft.txt>"%userprofile%\Desktop\draft.txt"
Also you can create .txt file and write in it text through Java code:
File directory = new File(System.getProperty("user.home")+"//Desktop//testing");
if (!directory.exists())
directory.mkdirs();
String content = "Writing text to draft.txt";
File file = new File(System.getProperty("user.home")+"//Desktop//testing//draft.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

create new document from template

I want to open a new document from a MS-Word template from my Java-App, but only manage to edit the template itself.
Here is my situation:
Inside my Jar file is a word template, that gets copied to a user-specified location, so he/she can edit it. Afterwards, the application can open this edited template, insert data into it and open it in word. This all works fine (using Apache-POI), but the last step is not entirely what I want.
Normally, when double-clicking a word-template, Word would open a NEW document (titled Document1) that is not saved anywhere yet. In my case, Word opens the word-template for editing (titled blablaMyTemplate), meaning the already saved template from which documents should be created. How do I manage to open a newly created document from the template using Java?
This is my code (try/catch and stream closing omitted):
File bbb = new File(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getParentFile().getAbsolutePath() + "/blablaMyTemplate.dotx");
if (!bbb.exists()) { //copy file to outside of jar for user editing
Files.copy(Buchungsbegleitblatt.class.getResourceAsStream("bbb.dotx"), bbb.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
File tmp = File.createTempFile("bbb", ".dotx"); //create tmp file to insert data
InputStream in = new FileInputStream(bbb);
OutputStream out = new FileOutputStream(tmp);
XWPFDocument document = new XWPFDocument(in);
//here, some data is filled into the document using Apache-POI (omitted, because it works fine)
document.write(out);
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(tmp); //this opens the template for editing, it does not create a new doc from template
}
The issue lies within the last line, but I have no idea what else I could call here.
To make it a little clearer, here is an image of the context menu I get on the template file and what is supposed to happen:
You have exactly described the problem already. Desktop.open will exactly do what it says. It will perform the open event for the called application which is assigned to the file type.
What you need is to perform the new event. This can be achieved in Word using startup command-line switches to start Word.
In the linked knowledge base entry you can find:
...
/ttemplate_name Starts Word with a new document based on a template
other than the Normal template.
...
To do so with Java either Runtime.getRuntime().exec or ProcessBuilder can be used. With both I would recommend first to start the command interpreter CMD as a shell and use the start command from this to start the application. So we avoid the need to know the exact path to the application.
Examples:
import java.io.*;
class RuntimeExec {
public static void main(String[] args) {
try {
// Execute a command as a single line
File f = new File("C:/Users/axel/Documents/The Template.dotx");
System.out.println(f.getAbsolutePath());
String cmd = "cmd /C start winword.exe /t\"" + f.getAbsolutePath() + "\"";
Process child = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UseProcessBuilder {
public static void main(String[] args) {
try {
//use ProcessBuilder to have more control
File f = new File("C:/Users/axel/Documents/The Template.dotx");
System.out.println(f.getAbsolutePath());
String application = "winword.exe";
String switchNewFromTemplate = "/t";
String file = f.getAbsolutePath();
ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "start", application, switchNewFromTemplate+file);
Process process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is one possibility to not explicitly start the winword application. The start command has the feature to perform the default action according to the file extension with the given file if we give a empty string "" as the application name:
start "" "The name of the file.ext"
Example:
start "" "The name of the file.dotx"
This will perform the default action new in winword application which is related to the dotx extension in registry database.
So:
class RuntimeExec {
public static void main(String[] args) {
try {
// Execute a command as a single line
File f = new File("C:/Users/Axel Richter/Documents/The Template.dotx");
System.out.println(f.getAbsolutePath());
String cmd = "cmd /C start \"\" \"" + f.getAbsolutePath() + "\"";
Process child = Runtime.getRuntime().exec(cmd);
InputStream in = child.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UseProcessBuilder {
public static void main(String[] args) {
try {
//use ProcessBuilder to have more control
File f = new File("C:/Users/Axel Richter/Documents/The Template.dotx");
System.out.println(f.getAbsolutePath());
String file = f.getAbsolutePath();
ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "start", "\"\"", file);
Process process = pb.start();
InputStream in = process.getErrorStream();
int c;
while ((c = in.read()) != -1) {
System.out.print((char)c);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
One way to do this is to start a process on the template so that Windows will handle the opening, and use the default intent. It's been a while since I've touched Java, but if it's like C# it will be something like new Process(tmp).Start().
Though, I'm not really sure if this is what you're looking for, exactly.

Using ProcessBuilder to make a jar file isn't completing

I am trying to compile a jar file from within a Java program. When I run the code it starts to build the jar file and saves about 24k of it then the execution just seems to stop and wait (I am using Process.waitFor() and the program isn't finishing its execution). When I force the program to stop the size of the jar file jumps to about 45k. The jar should be about 1300k.
I tried creating a batch file and then calling the batch file with my ProcessBuilder but the same issue occurs. The batch file when run by itself works perfectly.
This is the code I have so far:
public static void buildJar() {
List<String> jarCmdArgs = new ArrayList<>();
jarCmdArgs.add("jar");
jarCmdArgs.add("cvfM");
jarCmdArgs.add(ROOT_DIRECTORY + File.separator + "my_jar.jar");
jarCmdArgs.add(".");
// jarCmdArgs.add("cmd.exe");
// jarCmdArgs.add("/C");
// jarCmdArgs.add(ROOT_DIRECTORY + File.separator + "make_jar.bat");
ProcessBuilder pb = new ProcessBuilder(jarCmdArgs);
pb.directory(new File(SRC_DIR_PATH));
try {
Process p = pb.start();
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This is the contents of the batch file:
//cd to my working dir with all the files to put into the jar
jar cvfM my_jar.jar .

being able to read a file on command file using java

I have a program that works fine when it is run on eclipse (the program reads from a text file). However when it is complied and run on command line it can not find the text file I am reading from.
private void openfile()
{
try
{
file = new Scanner(new File("file.txt"));
}
catch(Exception e)
{
System.out.println("i hate command prompt");
}
private void readfile()
{
while(file.hasNext())
{
map_name = file.nextLine().split("\\s+");
}
}
private void closefile()
{
file.close();
}
can anyone explain how i can avoid this
You must place file.txt in the user.dir as specified by the File documentation. To determine what the user.dir is try printing out the property in your code, then placing the file in the directory.
System.out.println(System.getProperty("user.dir"));

.jar doesn't run external program

So i have a java project made in eclipse with sphinx voice recognition. If i say a certain word then it runs a .bat file.
if (resultText.equals("word")) {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("C:/c.bat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In Eclipse it works fine, but after i export the .jar and run it, if i say that specific word, it doesn`t run that .bat. So any ideas why this only runs my .bat file from eclipse and not from command line? Thanks
I am not sure about this but atleast try this solution once.
Try giving the .bat file path as C:\\c.bat and then try again.
Try adding something like:
File f = new File("c:/c.bat");
if(f.exists()) {
// execute the file
Process process = runtime.exec(f.getAbsolutePath());
process.waitFor();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
// check the streams for errors
} else {
// log error
}
hth

How can I set/update PATH variable from within java application on Windows?

Something equivalent to this command line:
set PATH=%PATH%;C:\Something\bin
To run my application, some thing has to be in a PATH variable. So I want at the program beginning catch exceptions if program fails to start and display some wizard for user to select the installation folder of a program that needs to be in a PATH. The I would took that folder's absolute path and add it to the PATH variable and start my application again.
EDIT:
That "something" is VLC player. I need it's installation folder in PATH variable (for example: C:\Program Files\VideoLAN\VLC). My application is single executable .jar file and in order to use it, VLC needs to be in a PATH. So when the user first starts my app, that little wizard would pop up to select the VLC folder and then I would update PATH with it.
You can execute commands using the Process object, you can also read the output of that using a BufferedReader, here's a quick example that may help you out:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String args[]) {
try {
Process proc = Runtime.getRuntime().exec("cmd set PATH=%PATH%;C:\\Something\\bin");
proc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = reader.readLine();
while (line != null) {
//Handle what you want it to do here
line = reader.readLine();
}
}
catch (IOException e1) {
//Handle your exception here
}
catch(InterruptedException e2) {
//Handle your exception here
}
System.out.println("Path has been changed");
}
}

Categories

Resources