How to execute vbs file in java, which directory contains spaces - java

Im currently coding a program, but i need to make it execute a vbs file. TempDir.vbs. However, the directory to this file contains spaces.
Unfortunally, all other topics dont work when the directory contains spaces.
In my case:
C:\\Users\\"the user"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup
the code im currently using is:
Runtime.getRuntime().exec("wscript.exe " + "\"\"\"" + path + "\"\"\"" + "TempDir.vbs");
So, how can i execute the file TempDir.vbs.

Instead of using Runtime.exec(String), use Runtime.exec(String[]):
Runtime.getRuntime().exec(new String[] {
"wscript.exe",
path + "TempDir.vbs"
});
As mentioned in a comment to a now deleted answer by ziesemer, if the .vbs file is a console script, you might need to use cscript.exe. See this for explanation: Difference between wscript and cscript

Related

findstr not working in Java, How to fix it?

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.

unable to rename file with dynamic paths in jmeter using beanshell

I am trying to rename a file using beanshell sampler in jmeter
I have simple code where I am trying to assign the path (dynamically change filename and append to the path) to a file func.
String filename= "\"C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck"+024+".xlsx\"";
File file = new File(${filename});
File file2 = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck025.xlsx");
boolean success = file.renameTo(file2);
if (!success) {
log.info "file renamed successfully"
}
I am able to successfully renamed the file if I use a static filepath like
File file = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck025.xlsx");
File file2 = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck026.xlsx");
boolean success = file.renameTo(file2);
if (!success) { log.info "file renamed successfully" }
error:
inline evaluation of: ``String filename= ("C:\Users\Thaneer_M\Downloads\apache-jmeter-2.13_save\JmeterR . . . '' Token Parsing Error: Lexical error at line 1, column 24. Encountered: "U" (85), after : "\"C:\\"
the files name change dynamically and I want to be able to create filepath string dynamically by appending integer to the file name.
Can some one please advise.
thank you
Few suggestions:
Remove starting and ending \", they're not required
Make sure you have double slashes everywhere. Alternative cross-platform option will be replacing slashes with File.separator like:
"Users" + File.separator + "Thaneer_M" + File.separator + "..."
Beanshell treats 024 is an Octal integer, make sure you use it correctly and know what you're doing. If you need exactly "024" value it's better to pass it as a string
Some debugging options:
log.info("something") will print the line to jmeter.log file. This way you can see variable values
Placing debug(); line at the very beginning of your Beanshell script will trigger debug output to stdout
surrounding your code with try/catch and printing exception stacktrace to jmeter.log provides more information on Beanshell errors, like:
try {
//your code here
}
catch (Throwable e) {
log.error("Error in Beanshell", e);
}
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more detailed information on Beanshell scripting in JMeter.
Same thing happened for me. To solve the problem I performed the following thing in Beanshell code:
Open the source file.
Copy the contents to a temp file
Delete the source file using file.delete()
Create a new file with the same name as the source file.
Copy contents of temp file in this new file.
Delete temp file.
I know this is not the best approach but this worked in jmeter 3.0.
Thanks,
Sumit Pal.

Split and rename java created xml file

I'm creating an xml-file in java using jaxb and XmlStreamWriter. This will become a very large file and has to be split into several pieces of max. 200MB. These pieces shouldn't be readable xml anymore.
The name of this file is very specific using the date and several parameters and at the end they're numbered like this: '3.1', '3.2', '3.3' where the first number is the number of chunks created and the second number is the following-number of the file. The first part of the filename (apart from the numbering) is created in the java application.
Now I want to create a UNIX script that calls the java application with the needed parameters, splits the file and renames the chunks.
I know the commands to call the java application and to split and rename files but I don't know how to combine them because I only now the filename in the Java application so I can't decide which file has to be split and renamed.
Does anyone have an idea how to deal with it?
EDIT:
Ok I'll try to be a bit less vague.
The application I created creates very large xml-files. The name of this files are in the following format: FI.DB2P.107601.20130130.20010.T.1.1 . This name contains some identification numbers and the date when the file is created. The first part of the name is created in the Java application like this: FI.DB2P.107601.20130130.20010.T.
Now this file should be split into several chunks of max. 200 MB each. Then the created chunks should have the same name as the 'base-file' but they have to end with 'T.3.1', 'T.3.2' and 'T.3.3' for example.
My question now is how I can obtain the filename of the file created by the java application in the Unix script. The filename is pretty complex and contains data from the database so I can't define the name in the Unix script.
I hope it's a bit clearer now.
Is it not the case that your Java process will call the Unix script and therefore will be able to pass it the filename on the command line.
The Unix script can take the filename and run something like split on it and then fix-up the filenames to those that your Java process is expecting.
Unless I misunderstand your question that should be fairly easy to do.
When you create your XMLStreamWriter you know (hopefully) the name of the file:
String fileName = "FI.DB2P.107601.20130130.20010.T.1.1";
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(fileName ));
Then it's not a problem to pass this name as a parameter to your shell script:
Runtime.getRuntime().exec("yourscript.sh " + fileName);
yourscript.sh will have code to split the file and add incrementing variable to the file name, something like this might work:
#!/bin/bash
split -b 200m -a 5 "$1" splited_file
i=1
for file in splited_file*
do
mv $file $1_${i}
i=$(( i + 1 ))
done
ps: this script is not thread safe :)

Get name of running Jar or Exe

What I need to do is get the name of the running jar/exe file (it would be an EXE on windows, jar on mac/linux). I have been searching around and I can't seem to find out how.
How to get name of running Jar or Exe?
Hope this can help you, I test the code and this return you the full path and the name.
Maybe you want to play a little more with the code and give me some feed back.
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌
This was found on a similar but not == question on stackoverflow
How to get the path of a running JAR file?
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌
returns simple path in the compiled application and an error in jar:
URI is not hierarchical
My solution is:
private File getJarFile() throws FileNotFoundException {
String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n" + path);
}
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return new File(path.substring(0, path.lastIndexOf('!')));
}
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath());
Should give you the jar.
as for the exe, as I'm assuming you're using some sort of wrapper, you'll need to know the name of the exe before it's run. Then you could use something like :
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
Try the following
System.getProperty("java.class.path")
Using Lunch4j you can add an image name for exe file by editing generated xml, you have to change tag value true from false to true

Having an Issue with running gnuplot processes from Java

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.

Categories