I'm working on a project and part of it must search words in some raw files of tagged text. For this, I'm trying to use the "findstr" function but It's been giving me lots of trouble.
The file contains text in spanish so in order to deal with the special characters I have to use the "findstr" function with some options.
I'm trying to run the command by ProccesBuilder and Process class but nothing It's happening.
I suspected that maybe there was a problem with the actual work directory so I changed It in the ProcessBuilder object that I have but with no results.
private static void findWordData(String filename){
try{
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.command("cmd.exe","/c",procs);
proBuild.directory(new File("resources/TextData/SPA/"));
Process p= proBuild.start();
} catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
The expected result is that the command reads the word in the file after the /g: tag and then searches it through all the files that begin with "spanishEtiquetado". Finally, the results should be written in a file "results.txt":
Thanks for your time.
EDIT:
Ok this is weird.
As you can read in the comments, I created a new project so I could test things better and something weird It's happening.
Right now, I have the aux_string.txt, results.txt and the spanishEtiquetado file both in the root folder of the project and src folder of the project.
As code I have been testing two options:
First, the one that SuperMario48 posted a bit modified:
Runtime.getRuntime().exec("cmd /c findstr /g:aux_strings.txt spanishEtiquetado* >results.txt");
The second one is the one I was using before:
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.directory(new File("src/"));
proBuild.command("cmd.exe", "/c", procs);
Process p = proBuild.start();
If the first one is executed the files that are located in the root folder are treated by the command and thus the results.txt file in the root folder is modifided with the wanted results.
Now, If I use my old code the directory change happens and a results.txt is written in the src folder but it's empty because the other necesary files are not readed, not even those that are outside the src folder.
I don't hace any idea of what is happening, any help appreciated.
Maybe try this. Just another kind of executing an external process.
Runtime.getRuntime().exec("cmd /c findstr /g:" + filename + " spanishEtiquetado* >results.txt");
Replace your try block with that to test.
Related
I want to concatenate two dos commands in a java program. First I want to change directory then list the files and folders in that. So I wrote that like
try
{
Process process = UI.this.rt.exec("cmd.exe /c cd C:\\Users & start dir");
process.waitFor();
InputStream in = process.getInputStream();
while (in.read() != -1) {}
}
catch (Exception e)
{
System.out.println(e);
}
But this is not working. When I execute this in desktop it is not change the directory and display the files and folders which is in the desktop. Could you please help me to fix this problem? I'm using windows 7 machine.
Thanks
Isuru Liyanage
Write the commands to a batch file on the disk and execute the batch.
If you don't want to have such a batch on the disk, create it on demand and delete it after usage.
Or just use the java build-in features to list files.
EDIT
But your code works. I tried it.
It opens a dos-box an lists the directory after changing the directory.
You can use ProcessBuilder to set the working directory of the Process you exec later.
Or, do as suggested else-thread and use the Java API for listing files in a directory, which is saner.
While creating a process you can pass a string array of commands as below:
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = " cd c:\\Users && dir";
Process p = Runtime.getRuntime().exec(command);
Drop the start, it runs files in a new window. Plus as there in no cmd in the NEW command DIR won't be recognised as a command. If you must use start for some reason add cmd /c to the dir part as well.
also dir c:\users is all you actually need to do. No need or reason to change directory.
I need some help with using the following code to modify and existing jar file:
String command = "cmd /c jar uf " + dirToModify + " " + Main.getMain().outputLocate.getSelectedFile();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
dirToModify = "C:\\Users\\Me\\Desktop\\myfile.jar"
Main.getMain().outputLocate.getSelectedFile() = "C:\\Users\\Me\\Desktop\\myfolder"
Basically I want to add the files/folders from myfolder to myfile.jar but with the above code it will add a shortcut to my C: drive not the files from myfolder.
Also I did look at other posts but none help me with this problem.
Any help with this would be greatly appreciated.
I'd suggest, first checking, if adding one file, at a time, is working with this code. This will make clear if problem is in 'folder addition' or 'file addition'.
If file addition doesn't work, your basic jar update logic is broken. So you can ask for solution to that problem.
If file addition works, try recursively adding all files from destination folder.
I'm having some trouble running gnuplot processes from Java. I'm creating a gnuplot script file, and then running it from within a java program. I've tried using both Process Builder and building a precess using Runtime.getRuntime().exec("blah blah..."), and neither have the full capability to work. The funny thing is is that using Runtime to make the process works almost perfectly, as long as the image file I'm creating via gnuplot isn't being saved to a directory without a space in it's name. ProcessBuilder doesn't work at all, however, and gives me the error: "CreateProcess error=2, The system cannot find the file specified"
It's taken me far too long to figure this stuff out, and so any help would be appreciated.
The code I use is here:
File script = new File("Demo.plt"); //Script file that outputs to a PNG file
//This works as long as the script file doesn't output to a png with a space in it's filepath
Process aProcess = Runtime.getRuntime().exec("gnuplot " + script.toString());
Thread.currentThread().sleep(1000);
aProcess.waitFor();
//This doesn't work at all
ProcessBuilder builder = new ProcessBuilder("gnuplot " + script.toString());
builder.redirectErrorStream(true);
Process process = builder.start();
And I know that the script works if run outside of Java, regardless of the spaces in the output line. I've even tried using '\ ' (the escape character for a space) and that doesn't work either. In fact, here is the code that I use:
String graphName = "DemoGraph";
//Isolate the FilePath
String path = script.getPath();
path = path.replace(script.getName(),"");
path = path.replace(File.separator, "\\\\"); //Gets around any parsing errors in filepaths on Windows
path = path.replace(" ", "\\ "); //Should get around parsing errors with spaces in gnuplot, but it seems to be irrelevant.
scriptFileWriter.write("set output \"" + path + graphName + ".png\"\r\n");
It's got to be an issue with java, because the scripts run from the Windows command line, and from the gnuplot command line, and frun being run by double-clicking the
I forgot to put quotes around the file name. It was a STUPID error.
Am trying to execute the a bat file with some arguments through a JAVA programmes . the arguments are file name with full path, And this path had some folder name with space, which are creating issue and giving me the following error
Error: 'D:\Documents' is not recognized as an internal or external
command
the code is as below
String command = "D:\Documents and Settings\ A.bat" + " " D:\Documents and Settings\B.xml
1. process = Runtime.getRuntime().exec(new String[] {"cmd.exe","/c",command});
2. process.waitFor();
3. exitValue = process.exitValue();
You need to escape the \ in your string (i.e. doubling them: D:\\Documents), but that is not the problem. You can try to escape the spaces Documents\\ and\\ Settings or you use the exec method that does this for you. Just dont build the command line by yourself. Better use ProcessBuilder for starting processes.
String command = "\"D:\Documents and Settings\\" A.bat" + " \"D:\Documents and Settings\B.xml\""
Escape double quotes, so you can include double quotes in the literal, to give:
cmd.exe /x "D:\Documents and Settings\" A.bat "D:\Documents and Settings\B.xml"
I was trying to do the same thing. I googled whole day but didn't make it work. At Last I handled it in this way, I am sharing it if it comes to any use of anybody :
String command = "A.bat D:\\Documents and Settings\\B.xml";
File commandDir = new File ( "D:\\Documents and Settings ");
String[] cmdArray = { "cmd.exe", "/c", command };
1. Process process = Runtime.getRuntime().exec( cmdArray, null, cmdArray );
2. process.waitFor();
3. exitValue = process.exitValue();
I've spent a while searching on SO and the wider Internet and was about to post this as a new question when I came across this, which does seem identical to my issue...
I am trying to call a Windows batch file from Java. The batch file takes several arguments but just the first, which is a path to a data file, is of relevance to this problem. The cut-down command line that I have been experimenting with is essentially:
cmd /c c:\path\to\my\batchfile.bat c:\path\to\my\datafile.mdl
I'm using Apache Commons Exec which ultimately delegates to Runtime.getRuntime().exec(String[] cmdarray, String[] envp, File dir), the 'correct' version as opposed to the overloaded versions taking a single String command. Quoting of the arguments when they contain spaces is therefore taken care of.
Now, both the path to the batch file and/or the path to the data file can have spaces in them. If either the path to the batch file or the path to the data file have spaces in, then the batch file is executed. But if both have spaces in them then the path to the batch file is truncated at the first space.
This has to be a (Java or Windows?) bug, right? I've debugged right down to the native call to create() in java.lang.ProcessImpl and all seems ok. I'm on JDK1.6.
I´m using Mac OS Lion, with java version 1.6.0_26
I'm making a small app for Mac in Java with a main menu for the user, so he can choose several options.
One of them is install an app using a .pkg
Everything was working fine with these commands:
File instFolder = new File(System.getProperty("user.dir") + "/foldername/appInstaller.pkg");
String s = "open "+ instFolder.toString();
Process p = Runtime.getRuntime().exec(s);
Then I realized that there is a problem when foldername has spaces or if I copy this java file with the needed subfolders to a USB pen drive with "NO NAME" as name (or some name with spaces).
Because s will become something like:
open /Volumes/NO NAME/foldername/appInstaller.pkg
or
open /Users/user1/Desktop/folder name/appInstaller.pkg
So when you run the p process, the command will finish where the first space appears on the path
open /Volumes/NO
or
open /Users/user1/Desktop/folder
To try to fix this I changed the s definition for something like this:
String s = "open "+ "\"" + instFolder.toString() + "\"";
It stopped working fine. The strange thing is that if i copy the s value (after creating the s variable) and paste it in the terminal it works:
open "/Users/user1/Desktop/folder name/appInstaller.pkg"
but running it from Java it does't work.
Could you help me, please?
Thanks.
In order to properly escape arguments, you can use the following:
Runtime.getRuntime().exec(new String[] { "open", instFolder.toString() });
Though I would probably to use the more modern ProcessBuilder:
ProcessBuilder pb = new ProcessBuilder("open", instFolder.toString());
Process p = pb.start();
int exitCode = p.waitFor();
Though this may be worth a read depending on what you want to do with the processes output.
Note: edited to reflect question in comment
it seems your path does not have quotes when turned into the shell.
You should probably add "'" on both sides of your path, so the final shell command will look like:
open 'your path'
instead of
open your path
Here's a little trick that came out from the answers mentioned above:
ProcessBuilder pb = new ProcessBuilder(commandString.split(" "));
Say commandString = "killall Mail" then the split will separate the words making it a String[] parameter to the ProcessBuilder.