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))
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'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.
here is my code:
File file1 = new File("");
System.out.println(file1.exists()); // why the output is false?
System.out.println(file1.getAbsolutePath());
// assume that my current path is "d:/xxx/yyy"
File file2 = new File(".");
System.out.println(file2.getPath()); // i want to get ""
// but i actually get ".",
// which is not i want.
// so how can i get ""
to sum up, what i want is an object file of class File, which when i call
file.getPath() it returns ""
and when i call file.exists() it returns true;
If you really just want to have the current working directory in a string, you can simply use System.getProperty("user.dir"), see System Properties.
Otherwise you'll have to use . for the "current working directory" and use File#getCanonicalPath() the get the canonical representation of this File object. Also see File#getCanonicalFile().
To your first question: File("") is a valid path and is equivalent to System.getProperty("user.dir"). It is not a valid file or directory in that path (it still doea have a path though. This is a completely relative path, so when you call getPath() it will return an empty string since no file found by the name "".
Your second question "." is a directory, it exists, and it also has a relative path of "", so when calling getPath you will see the path "" + the directory name "."
If a file exists in the same directory where a Java application is running and I create a File object for that file the Java File methods for the path of the file include the filename as well. Code and output are below.
If this was a bug in the JDK version I'm using someone would surely have seen it by now.
Why do File.getAbsolutePath() and File.getCanonicalPath() include the file name? The Javadocs indicate that the directory name should be returned.
import java.io.File;
import java.io.IOException;
public class DirectoryFromFile {
private void getDirectoryOfFile(String fileName) throws IOException{
File f = new File(fileName );
System.out.println("exists(): " + f.exists());
System.out.println("getPath(): " + f.getPath());
System.out.println("getAbsolutePath(): " + f.getAbsolutePath());
System.out.println("getParent(): " + f.getParent() );
System.out.println("getCanonicalPath(): " + f.getCanonicalPath() );
System.out.println("getAbsoluteFile().getCanonicalPath(): " + f.getAbsoluteFile().getCanonicalPath() );
String dirname = f.getCanonicalPath();
System.out.println("dirname: " + dirname);
File dir = new File(dirname);
System.out.println("dir: " + dir.getAbsolutePath());
if (dirname.endsWith(fileName))
dirname = dirname.substring(0, dirname.length() - fileName.length());
System.out.println("dirname: " + dirname);
File dir2 = new File(dirname);
System.out.println("dir2: " + dir2.getAbsolutePath());
}
public static void main(String[] args) {
DirectoryFromFile dff = new DirectoryFromFile();
try {
dff.getDirectoryOfFile("test.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here' the output:
exists(): true
getPath(): test.txt
getAbsolutePath(): C:\dean\src\java\directorytest\directory.from.file\test.txt
getParent(): null
getCanonicalPath(): C:\dean\src\java\directorytest\directory.from.file\test.txt
getAbsoluteFile().getCanonicalPath(): C:\dean\src\java\directorytest\directory.from.file\test.txt
dirname: C:\dean\src\java\directorytest\directory.from.file\test.txt
dir: C:\dean\src\java\directorytest\directory.from.file\test.txt
dirname: C:\dean\src\java\directorytest\directory.from.file\
dir2: C:\dean\src\java\directorytest\directory.from.file
So far the only way I've found to get the directory in this case is to manually parse off the file name.
Does the File class have a way to get the directory name in this case (where a File that exists in the current directory is created without specifying a directory)?
Why do File.getAbsolutePath() and File.getCanonicalPath() include the
file name? The Javadocs indicate that the directory name should be
returned.
No, they don't. If you'd care to point out why you think they do, someone can probably identify the mistake in your reasoning. Also, if you specify exactly what you'd like to see for output given some particular input, we can help you out there, too. Your question title seems strange, too, since your problem seems to be that it is returning the full path to a file.
Edit: I think I understand the source of your confusion. A File represents a file system path in a platform-agnostic way. It can be a path to a file or to a directory. It also always represents the same path, though not necessarily the same absolute path. This is a very fine distinction but a very important one. A File object representing a relative path is always relative. Given a File representing a relative path, you can get the current corresponding absolute path using getAbsolutePath(). This doesn't, however, alter the fact that the File represents a relative path. Further invocations of getAbsolutePath() on the same File object may return different values. Consider, for example:
// A relative file
File foo = new File("foo.txt");
// Resolve relative file against CWD
System.out.println(foo.getAbsolutePath());
// Output: D:\dev\projects\testbed\foo.txt
System.setProperty("user.dir", "C:\\somewhere");
// Resolve relative file against new CWD
System.out.println(foo.getAbsolutePath());
// Output: C:\somewhere\foo.txt
// Get an absolute file
File absoluteFoo = foo.getAbsoluteFile();
// Show absolute path
System.out.println(absoluteFoo.getAbsolutePath());
// Output: C:\somewhere\foo.txt
System.setProperty("user.dir", "D:\\somewhere-else");
// An absolute path doesn't change when the CWD changes
System.out.println(absoluteFoo.getAbsolutePath());
// Output: C:\somewhere\foo.txt
It should be clear now that the path a File represents is only that: a path. Further, a path can be composed of zero or more parts, and calling getParent() on any File gives back the path of that File with the last path element removed unless there isn't a "last path element" to remove. Thus the expected result of new File("foo").getParent() is null since the relative path "foo" has no parent.
From the example and explanation above, you should be able to see that the way to get the containing directory when you've created relative-path File object is with
String absoluteParentDirPath = someRelativeFile.getAbsoluteFile().getParent();
with the caveat that the "absolute path" depends on your environment at the time.
Additional note: Since File is Serializable, you could write a relative-path file to disk or send it across a network. That File, when deserialized in another JVM, will still represent a relative path and will be resolved against whatever the current working directory of that JVM happens to be.
The behaviour is expected. The documentation does not mention that the filename is not included.
Perhaps you are confused by the difference between getAbsolutePath() and getAbsoluteFile(). It's that the latter returns a File instance.
I'm not sure why you think the Javadoc says that it returns the directory name.
Here is the Javadoc --
An abstract representation of file and directory pathnames.
User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:
An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX root directory, or "\\" for a Microsoft Windows UNC pathname, and
A sequence of zero or more string names.
The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The empty abstract pathname has no prefix and an empty name sequence.
http://download.oracle.com/javase/6/docs/api/java/io/File.html#getAbsolutePath%28%29
Returns the absolute pathname string of this abstract pathname.
In addition to the existing answers with regards to getAbsolutePath and getCanonicalPath, please also note, that File.getParent() does not mean "parent directory" it merely refers to the parent file object that was used to create the file.
For example, if the file object can be created as such:
File dir = new File("/path/to/a/directory");
File f1 = new File(dir, "x.txt");
File f2 = new File(dir, "../another/y.txt");
File f3 = new File("z.txt");
f1 would refer to /path/to/a/directory/x.txt, it's parent is dir (/path/to/a/directory)
f2 would refer to /path/to/a/directory/../another/y.txt, it's canonical path would be /path/to/a/another/y.txt, but it's parent is still the reference to dir (/path/to/a/directory)
f3 would refer to z.txt in the current directory. It does not have a parent file object, so f3.getParent() or f3.getParentFile() would return null.
path is the full path
if you only want the directory you need to call file.getParent()
When I pass File file to a method I'm trying to get its full path like file.getAbsolutePath(); I always get the same result no matter which one I use either absolute or canonical path PATH_TO_MY_WORKSPACE/projectName/filename and it is not there, how can I get exact location of the file?
Thank you
DETAILS:
Here is some code and this solutions(its bad but its working):
private static void doSomethingToDirectory(File factDir) throws IOException {
File[] dirContents = factDir.listFiles();
if(factDir.isDirectory() && dirContents.length > 0){
for (int i = 0; i < dirContents.length; i++) {
for (String str : dirContents[i].list()) {
if(str.equals(TEMP_COMPARE_FILE)){
process(new File(dirContents[i].getAbsolutePath() + "\\" + str));
}
}
}
}
}
I'm looping trough directories where factDir is src/main, I'm seeking toBeProcessed.txt files only that is TEMP_COMPARE_FILE value and I'm sending them to process method which reads the file and does processing of it.
If someone could better solution I'd be greatful
This quote from the Javadoc might be helpful:
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
I interpret this so that if you create your File object with new File("filename") where filename is a relative path, that path will not be converted into an absolute path even by a call to file.getAbsolutePath().
Update: now that you posted code, I can think of some ways to improve it:
you could use a FilenameFilter to find the desired files,
note that list and listFiles return null for non-directory objects, so we need an extra check for that,
you could also use listFiles() again in the inner loop, thus avoiding the need to create new File objects with hand-assembled paths. (Btw note that appending \\ manually to the path is not portable; the proper way would be to use File.separator).
The end result is
private static void doSomethingToDirectory(File factDir) throws IOException {
if (factDir.isDirectory()) {
for (File file : factDir.listFiles()) {
if (file.isDirectory()) {
for (File child : file.listFiles(new MyFilter())) {
process(child);
}
}
}
}
}
class MyFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.equals(TEMP_COMPARE_FILE);
}
}
Note that this code mimics the behaviour of your original piece of code as much as I understood it; most notably, it finds the files with the proper name only in the direct subdirectories of factDir, nonrecursively.
I think there is a way it may help you if and only if the file is in the program directory.
first you get the program directory by :
new File(".").getCanonicalPath()
then :
if file is inside a specific directory like folder\\filename
the full path will be
(new File(".").getCanonicalPath() + "\\folder\\filename")
or if file is directly inside the program directory:
the full path will be
(new File(".").getCanonicalPath() + "\\filename")
i wish this answer help you :)