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.
Related
The following code file.renameTo(new File(newPath)); dosen't rename all the files properly it skips over some I have even used Files.move(file.toPath(), Paths.get(newPath)); but i get an exception error in eclipse saying java.nio.file.FileAlreadyExistsException which i think is occurring because there are sets of files that when they are cut off they will have the same name is there a way to bypass this error in eclipse or fine tune the renameTo()?
I also have tried .substring(0,22);, name.replaceFirst("-2017.*", ""); and
name.substring(0, file.getName().indexOf("-2017") same result.
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
for(File file:filesInDir) {
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));
or
Files.move(file.toPath(), Paths.get(newPath));
You can not rename a particular file to a file name that already exists within the folder you are renaming the file in. IMHO ... Even if you can, you shouldn't for a bunch of common sense reasons.
In other words, if we have a folder (directory) named: All_My_Files and in this folder we have two text files, one is named MyFile-2016.txt and the other is named MyFile-2017.txt. Now, we want to rename each of these two files so that the dash and the year (ie: -2016 or -2017) from each file name no longer exists. Essentially what you will end up trying to do is have both file names be MyFile.txt which is not allowed. Your first rename will be fine since on the first go at it there is no file within the folder named MyFile.txt but once the second rename attempt is done on the second file name it's simply going to fail since the name MyFile.txt already exists within that folder which was done from the first rename attempt. This not a code problem, this is an issue with the local file system. Those are the rules of the local file system (No file can have the same name within the same folder). Look at the file names you are going to rename, are there any that will actually create the very same file name once you remove the unwanted text? If there are then those will fail to rename.
The same applies to Moving files. You can not move a file to a folder (directory) that already contains a file with the very same name. The file system rule above applies. You can however overwrite the existing duplicate file name within the destination path if it exists during a move if you tell the Files.move() method to do so:
Files.move(sourcePathAndFileName, destinationPathAndFileName,
StandardCopyOption.REPLACE_EXISTING);
You will need to import:
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
Keep in mind though, before you blatantly overwrite an existing file you better make pretty sure that this is what you want to do. Prompting the User to carry out an overwrite would be a normal course of action but doesn't necessarily need to be the case for specific in house operations.
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.
I'm trying to list a directory's contents, and rename certain files.
public void run(String dirName) {
try {
File parDir = new File(dirName);
File[] dirContents = parDir.listFiles();
// Rename if necessary
for(File f : dirContents) {
System.out.println("f is:\n" + f.toString());
String name = f.getName();
String subbedName = name.replaceAll("\uFFFD", "_");
System.out.println("\n" + "name = " + name + ", subbedName = " + subbedName + "\n");
if(!name.equals(subbedName)) {
File newFile = new File(f.getParentFile(), subbedName);
System.out.println("newFile is:\n" + newFile.toString());
if(!f.renameTo(newFile))
System.out.println("Tried to change file name but couldn't.");
}
}
}
catch(Exception exc1) {
System.out.println("Something happened while listing and renaming directory contents: " + exc1.getMessage());
}
}
When I run this, I get "Tried to change file name but couldn't." I don't believe that Java is considering these files to be "open", so I don't think that's the reason. I've even ran chmod 777 myDir where myDir is the value of the dirName string passed into the run method.
What am I missing here? Why won't Java rename these file(s)? These are CentOS machines.
Edit: Added printouts for both f and newFile, which is as follows:
f is:
/root/path/to/mydir/test�.txt
newFile is:
/root/path/to/mydir/test_.txt
You need to create your new File object with the full pathname of those files. So
String name = f.getName(); // gets the name without the directory
should likely be:
String name = f.getAbsolutePath();
(your search/replace may need to change)
The problem is that f.getName() returns the last name component of the path that is represented by f. You then massage this String and turn it back into a File. But the File now represents a path relative to the current directory, not the directory containing the original path.
As a result your code is actually attempting to rename the files from dirName into the application's current directory. That could fail because files already exist in the current directory with those names, or because the dirName and the current directory are in different file systems. (You cannot rename a file from one filesystem to another ... you have to copy it.)
Please note that a File in Java represents a pathname, not a file or a folder. In your code, the f objects are the pathnames for file system objects (either files or folders) in the directory denoted by the String dirname. Each of these f objects will have a directory part.
There is more than one way to fix your code; for example
change name = f.getName() to name = f.toString()
change new File(subbedName) to new File(f.getParentFile(), subbedName)
I have an alternative / additional theory.
The pathname of the file containing the \uFFFD character is coming out as "mojibake"; i.e. the kind of garbled text that you get when you display encoded text using the wrong encoding. And since we are seeing 3 characters of garbled text, I suspect that it is attempting to display the UTF-8 rendering of \uFFFD as Latin-1.
So my theory is that the same think is happening when the File.renameTo method is converting f to the form that it is going to provide to the system call. For some reason that is no clear to me, Java could be using the wrong encoding, and as a result producing a "name" for the original file that doesn't match the name of the file in the file system. That would be sufficient to cause the rename to fail.
Possibly related questions / links:
File name charset problem in java
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4733494 (Note that Sun decided this was not a Java bug, and most of the "me too" comments on the bug report are from people who do not understand the explanation ...)
f.getName(); only returns the name of the folder, not the full path. So subbedName becomes a relative path file. Try something with f.getCanonicalPath() instead.
I need to rename a file by replacing - with _ in the file name.
Suppose if a file name is ab-9.xml, it should be ab_9.xml.
renameTo() is not working for me. Is there any other way to do that? Here is my code:
File replaceCheracter(File file) {
File oldPath = new File(file.getPath())
String filePath = file.getPath()
if(filePath.contains("-")){
String newFilePath = filePath.replace("-", "_")
if(oldPath.renameTo(newFilePath)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
return oldPath
}
You should consider using the java.nio.file package:
final Path file = Paths.get("path\\to\\your-file.txt");
Files.move(file, file.resolveSibling(file.getFileName().toString().replace("-", "_")));
Used the very handy function Path#resolveSibling() as second argument for Files#move().
Explanation:
Path#resolveSibling() takes the directory path of the Path object it is called on, and swaps the last part (the actual file name) for the supplied argument (the new, modified file name in this case).
Using this behavior as second argument for Files#move() will result in a move where the source directory and the target directory are the same, thus it only renames the file.
See The Java Tutorials - File I/O for further information on this.
renameTo method accepts File as parameter not String
Change oldPath.renameTo(newFilePath) with
oldPath.renameTo(new File(newFilePath))
After reading that is it possible to create a relative filepath name using "../" I tried it out.
I have a relative path for a file set like this:
String dir = ".." + File.separator + "web" + File.separator + "main";
But when I try setting the file with the code below, I get a FileNotFoundException.
File nFile= new File(dir + File.separator + "new.txt");
Why is this?
nFile prints: "C:\dev\app\build\..\web\main"
and
("") file prints "C:\dev\app\build"
According to your outputs, after you enter build you go up 1 time with .. back to app and expect web to be there (in the same level as build). Make sure that the directory C:\dev\app\web\main exists.
You could use exists() to check whether the directory dir exist, if not create it using mkdirs()
Sample code:
File parent = new File(dir);
if(! parent.exists()) {
parents.mkdirs();
}
File nFile = new File(parent, "new.txt");
Note that it is possible that the file denoted by parent may already exist but is not a directory, in witch case it would not be possible to use it a s parent. The above code does not handle this case.
Why wont you take the Env-Varable "user.dir"?
It returns you the path, in which the application was started from.
System.getProperty(user.dir)+File.separator+"main"+File.separator+[and so on]