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.
Related
The code below works, but my problem is that the console output shows correctly for example:
3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMA-SUIQUARTER2
3-M-ALABAMAW-22017
3-M-ALABAMAW-22017
The output above show that my index is -2017 however when the actual file name is being change in the folder some of the File Names are skipped. For example
Orginal file name: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140
Console Output: 3-M-ALABAMA-SUIQUARTER2
Some of Files in folder unchanged: 3-M-ALABAMA-SUIQUARTER2-2017200346-CD6140
However some of the files in the folder have 3-M-BATTLECREEKMIW-22017-2017200346-CD619B and some are 3-M-ARLINGTONOHLOCALW-2-2017200346-CD61A8
So I think java is confused as to where to cut off when the actual change is being made in file alteration? can you help me?
for(File file:filesInDir) {
x++;
String name = file.getName().substring(0, file.getName().indexOf("-2017"));
String newName = name;
System.out.println(newName); // prints prints to file
String newPath = absolutePathOne + "\\" + newName;
file.renameTo(new File(newPath));
}
Okay there any other way to rename the files?
Yes. Use the newer NIO 2 classes, in particular the Files.move() method.
At the very least, replace file.renameTo(new File(newPath)) with:
Files.move(file.toPath(), Paths.get(newPath));
That will throw descriptive exception if move fails, instead of the false boolean return value from renameTo().
You should also change the rest of the code to use the newer classes. Although not required, it is recommended to do so.
I am trying to read package name from a jar file. My probem is that when I get URL, it contains unrecognized form to be recognized by windows file.
I read this solution. But this did not helped me. Convert URL to normal windows filename Java.
directoryURL.toURI().getSchemeSpecificPart() does not convert windows style.
This is my code.
// Get a File object for the package
URL directoryURL = Thread.currentThread().getContextClassLoader()
.getResource(packageNameSlashed);
logger.info("URI" + directoryURL.toURI());
logger.info("Windows file Name" + directoryURL.toURI().getSchemeSpecificPart());
// build jar file name, then loop through zipped entries
jarFileName = URLDecoder.decode(directoryURL.getFile(), "UTF-8");
jarFileName = jarFileName.substring(0, jarFileName.indexOf(".jar"));
// HERE Throws exception"
jf = new JarFile(jarFileName + ".jar");
while (jarEntries.hasMoreElements()) {
entryName = jarEntries.nextElement().getName();
logger.info("Entry name: " + entryName);
if (entryName.startsWith(packageNameSlashed)
&& entryName.length() > packageNameSlashed.length() + 5
&& entryName.endsWith(".class")) {
entryName = entryName.substring(packageNameSlashed.length() + 1);
packageClassNames.put(entryName, packageName);
}
}
This is log.
16-02-2015 14:02:15 INFO - URI jar:file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
16-02-2015 14:02:15 INFO Windows file Name file:/C:/SVN/AAA/trunk/aaa/client/target/server-1.0.jar!/packageName
A "jar:..." URL does not identify a file. Rather, it identifies a member of a JAR file.
The syntax is (roughly speaking) "jar:<jar-url>!<path-within-jar>", where the is itself a URL; e.g. a "file:" URL in your example.
If you are going to open the JAR file and iterate entries like that, you need to:
Extract the schemeSpecificPart of the original URL
Split the schemeSpecificPart on the "!" character.
Parse the part before the "!" as a URI, then use File(URI) to get the File.
Use the File to open the ZipFile.
Lookup the part after the "!" in the ZipFile ...
The answer by Stephen has all the elements you need.
With the getResource(package).getURI() or getResoucer(package).toFile you are getting the path to the resource.
Do substring on it to extract the part between file:// and ! this is the path to physical location of your jar of interest.
De new File on this sub-path and you have handle to your jar.
Jar is normal zip file, and process it as such (java.util.zip and there are manuals on the web).
List content of your zip file (now you may need to navigate using the bits behind ! sign in your original path), and you get your classes name.
I am not sure if this is the best way to achieve your goal, I would check how classes discovery (which is what you are trying to do, are implemented in some open source framework (for example tomcat uses it, JPA impelementation to find the entitities). There is also discovery project on apache but it seems to be dead for a while.
If I try to download file like like below it is getting downloaded here
client.retrieveFile("/" + filename, fos); // working
But if i try to to download FTP file to particular local directory as below it is not getting downloaded there. Can anybody tell me why this is happening ?
client.retrieveFile("C:\MydownloadedFiles" + filename, fos); // not working
Thanks.
Please escape the "\".
It should be:
client.retrieveFile("C:\\MydownloadedFiles" + "\\" + filename, fos);
In general I would recommend working with the constant File.separator, to support cross-platform.
Another idea I have in mind (please test it) is the following:
File downloadsDirectory = new File("c:","MyDownloadedFiles");
File retrievedFileOnLocalComp = new File(downloadsDirectory.getAbsolutePath(),filename);
client.retrieveFile(retrievedFileOnComp.getAbsolutePath(),fos);
Explanation-
The first line creates a download directory under the parent path of "c:"
The second line creates the file name to download to with parent directory equals to the absolute path of the result from the first line.
The third downloads to it.
You had an issue with rememembering to use "\\".
I suggest to use these three lines in order to solve this issue and to get rid of platform dependant decision on the slash-type.
I'm writing a program where I'm trying to create a new text file in the current directory, and then write a string to it. However, when trying to create the file, this block of code:
//Create the output text file.
File outputText = new File(filePath.getParentFile() + "\\Decrypted.txt");
try
{
outputText.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
is giving me this error message:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at code.Crypto.decrypt(Crypto.java:55)
at code.Crypto.main(Crypto.java:27)
Because of this I cannot write to the file because it naturally does not exist. What am I doing wrong here?
If you're working with the File class already, consider using its full potential instead of doing half the work on your own:
File outputText = new File(filePath.getParentFile(), "Decrypted.txt");
What's the value of filePath.getParentFile()? What operating system are you using? It might be a better idea to join both paths in a system-independent way, like this:
filePath.getParentFile() + File.separator + "Decrypted.txt"
It should be created as a sibling of the file pointed by filePath.
for example if
File filePath = new File("C:\\\\Test\\\\a.txt");
Then it should be created under Test dir.
So basically say i have a file that is simply called settings, however it has no extension, but contains the data of a text file renamed.
How can i load this into the file() method in java?
simply using the directory and file seems to make java think its just a directory and not a file.
Thanks
In Java, and on unix, and even on the filesystem level on windows, there is no difference in if a file has an extension or not.
Just the Windows Explorer, and maybe its pendants on Linux, use the extension to show an appropriate icon for the file, and to choose the application to start the file with, if it is selected with a double click or in similar ways.
In the filesystem there are only typed nodes, and there can be file nodes like "peter" and "peter.txt", and there can be folder nodes named "peter" and "peter.txt".
So, to conclude, in Java there is really no difference in file handling regarding the extension.
new File("settings") should work fine. Java does not treat files with or without extension differently.
Java doesn't understand file extensions and doesn't treat a file any differently based on its extension, or lack of extension. If Java thinks a File is a directory, then it is a directory. I suspect this is not what is happening. Can you try?
File file = new File(filename);
System.out.println('\'' + filename + "'.isDirectory() is "+file.isDirectory());
System.out.println('\'' +filename + "'.isFile() is "+file.isFile());
BTW: On Unix, a file file. is different to file which is different to FILE. AFAIK on Windows/MS-DOS they are treated as the same.
The extension should not make a difference. Can you post us the code you are using? And the error message please (stack trace).
Something along these lines should do the trick (taken from http://www.kodejava.org/examples/241.html)
//
// Create an instance of File for data file.
//
File file = new File("data");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}