How to rename file in a general way in java? - java

I have two File Object oldFile and newFile and I would like to exchange the corresponding file names. So I rename oldFile to a tmpFile name first. I get the oldFile's absolute path and append ".bak" for it:
String tmpFile = oldFile.getAbsolutePath().toString()+".bak";
oldFile.renameTo(new File(tmpFile));
The problem is that tmpFile contains the raw string of path,while the constructor of File class treat the '\' as the escape.So the tmpFile may be "D:\oldfile.java.bak",however what the constructor need is
new File("D:\\oldfile.java.bak");
How can I deal with it?

The constructor of File does NOT treat \ as escape. You need to escape \ with \ in a string literal. The String literal "\\" contains a single character: '\'.
String path = "D:\\oldFile";
System.out.println(path); // prints D:\oldFile
File f = new File(path);
System.out.println(f.getAbsolutePath()); // prints D:\oldFile

You have to escape the escapes with .replace("\", "\\") but if you have to do that then realize you don't have to use \ on Windows. Java supports / just as fine and it doesn't have these problems. You can do replace("\", "/") and it works just as well.
You also need to read and understand how to create new files in Java. File.createNewFile() is required to be called. Just creating a File object with the constructor doesn't actual create a file on the filesystem nor does it guarantee that a file at that location exists.

Related

Cant figure out Java find for an "abstract path"

I am working in eclipse trying to create a file.
This is my code:
File file = new File("C:\Users\Local Admin\Desktop\1.txt");
I copied the path I am using directly from the properties of the file but I keep getting the error
Invalid escape sequences.
I tried adding an extra "\" in front of each "\" but that didn't fix anything.
Any suggestions?
It should be either:
File file = new File("C:\\Users\\Local Admin\\Desktop\\1.txt");
Or:
File file = new File("C:/Users/Local Admin/Desktop/1.txt");
Replace "\" by either "\\" or "/".
Try this.
File file=new File("C:/Java/hello.txt");
Try storing the path of the file in a string variable and passing that string variable.Use "\\" if "\" doesn't works.
String filePath="your path";
File file=new File(filePath);

Java.io.file constructor to deal with UNC file path

When I try to use the JAR file in the UNC path, I find I met a problem. The constructor of java.io.file will always convert a UNC file path to local path.
For example, I try
String dirStr = "file:\\\\dir1\dir2\file.jar!Myclass";
File ff = new File(dirStr);
System.out.println(ff.toString());
I'll get output like: file:\dir1\dir2\file.jar!Myclass. But what I expect to get is file:\\dir1\dir2\file.jar!MyClass.
I tried to add more slashes in the dirStr, but it can't work. Because in the java.io.file, it'll call method to remove duplicated slashes.
And I try to use the URI to create the ff. But the output will be \dir1\dir2\file.jar!Myclass, which is not available to use JAR file successfully. I think the form of JAR must be start with the file: protocol to use parse the string ending with ! in above string \dir1\dir2\file.jar!Myclass.
Is there any way can new File() to get the pathname of File, i.e. ff, like file:\\dir1\dir2\file.jar!MyClass.
Since your input dir String is UNC type, i think you should use Java's URI.
Example code:
URI uri = new URI(dirStr);
System.out.println(uri.toString()); // If you want to get the path as URI
File ff = new File(uri.getPath()); // If you want to access the file.
The other better way is using Path:
URI uri = new URI(dirStr);
Path path = Paths.get(uri); // Or directly Path path = Paths.get(dirStr);
File ff = path.toFile(); // << your file here
path.toUri(); // << your uri path here
The constructor File(String) takes a path, not a URL. Remove the file: part and use two backslashes for every one in the actual filename, to satisfy the compiler's escaping rules. Or use the correct number of forward slashes.

Create directory at given path in Java - Path with space

I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
You should us \\ for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes / so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
You need to escape your path (use \\ in your path instead of \) and you also need to use String, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator) or accesing the equivalent field in the File class. Also check this question.
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();

Get file.separator of a specified file path

How do you get a file separator of a specified file/folder path?
In Java, we can write, for example
File f = new File("C:\\MyFolder\\MyText.txt");
Keep in mind this is a file representation (the file does not have to exist physically). So given any specified path, is there a method that can return the separator for that specified path only?
From the docs
The File.pathSeparator and File.pathSeparatorChar returns system dependent file separator, but what I want is the separator for a given path, like in the above case \, even if the above program is run and the path is not valid for *nix
I would start with System.getProperty("user.home"). And, you could use File.seperator like
File f = new File(System.getProperty("user.home") +
File.seperator + "MyText.txt");
but I would prefer File(String parent, String child) like
File f = new File(System.getProperty("user.home"), "MyText.txt");
System.out.println(f.getPath());
The separator character for File objects is always given by File.separator (or File.separatorChar). There is no way to construct a File object with an unusual separator; they always hold paths that are valid on the current system.
File f = new File("C:\\MyFolder\\MyText.txt");
After executing this line on Windows, f refers to a File object that refers to the file MyText.txt in the folder MyFolder on drive C:, as you probably intended.
But on Linux, f refers to a File object that refers to the file C:\MyFolder\MyText.txt in the current directory. (On Linux, backslashes are allowed in filenames)
Imagine if there was a way to do this. If you had a File constructed with new File("a/b\\c"), then how would you know whether it was referring to the file b\c in the folder a (with separator /), or the file c in the folder a/b (with separator \)?
It can't, so it should be clear that there is no reliable way to do this. If your program handles paths with unusual separators, then your program needs to handle them itself. File cannot do it for you.

renameTo() not working

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))

Categories