Java - Get final "destination" of a file - java

I was wondering, how can I find the final destination of a file?
For example, if I write this path:
C:\JavaDir\2ndDir\file.txt
The path would be simple, but if I type, for example:
C:\JavaDir\2ndDir\3rdDir\..\file.txt
Now, I can see that the destination would be ...\2ndDir\file.txt, but how can I run a command to check the destination?

What you want is the canonical path, which is unique for every single file. You basically just need to create a File object and run the getCanonicalPath() method to get what you want.
File f = new File(yourPath);
System.out.println(f.getCanonicalPath());
...checking for exceptions, yada yada.

Related

Access file without knowing absolute path, only knowing file name

I'm trying to use a file in my code but I don't want to have specify the absolute file path, only the file name, for example "fileName.txt".
I want to do this so I have the ability to use this code on different laptops where the file may be stored in different folders.
The code below is what I'm using at the moment but I receive a NoSuchFileException when I ran it.
FileSystem fs FileSystems.getDefault();
Path fileIn = Paths.get("fileName.txt");
Any ideas how to overcome this problem so I can find the file without knowing its absolute path?
Ideas on how to find the file without knowing its absolute path:
Instruct the user of the app to place the file in the working directory.
Instruct the user of the app to give the path to the file as a program argument, then change the program to use the argument.
Have the program read a configuration file, found using options 1 or 2, then instruct the user of the app to give the path to the file in the configuration file.
Prompt the user for the file name.
(Not recommended) Scan the entire file system for the file, making sure there is only one file with the given name. Optional: If more than one file is found, prompt the user for which file to use.
if you don't ask the user for the complete path, and you don't have a specific folder that it must be in, then your only choice is to search for it.
Start with a rootmost path. Learn to use the File class. Then search all the children. This implementation only returned the first file found with that name.
public File findFile(File folder, String fileName) {
File fullPath = new File(folder,fileName);
if (fullPath.exists()) {
return fullPath;
}
for (File child : folder.listFiles()) {
if (child.isDirectory()) {
File possible = findFile(child,fileName);
if (possible!=null) {
return possible;
}
}
}
return null;
}
Then start this by calling either the root of the file system, or the configured rootmost path that you want to search
File userFile = findFile( new File("/"), fileName );
the best option, however, is to make the user input the entire path. There are nice file system browsing tools for most environments that will do this for the user.

What is difference between File file = new File() and File file = new File.Paths.get().toFile()?

Is any difference? First solution has "new" and second hasn't. I see only this difference.
You should always use new File in this case.
(Also your second possibility will not work the way you use it here).
There are other cases where you for example only have a Path object and you'd like to convert it into a File. Then you would use the toFile method on the Path-Object to get a File back.
In your case you access the File, convert it into a Path and then back into a File, which isn't necessary at all.
For example if you have a Path and want the file from it:
//existing Path object
void receivePath(Path path) {
File = path.toFile();
}

Can I use File.createTempFile() to create a file with a non-random name

I want to create a temporary file (that goes away when the application closes) with a specific name. I'm using this code:
f = File.createTempFile("tmp", ".txt", new File("D:/"));
This creates something like D:\tmp4501156806082176909.txt. I want just D:\tmp.txt. How can I do this?
In this case, don't use createTempFile. The point of createTempFile is to generate the "garbage" name in order to avoid name colisions.
You should use File.createNewFile() or simply write to the file. Whichever is more appropriate for your use case. You can then call File.deleteOnExit() to get the VM to look after cleaning up the file.
If you want to create just tmp.txt, then just create the file using createNewFile(), instead of createTempFile(). createTempFile is used to create temporary files that should not have the same name when created over and over.
Also have a look at this post which shows a very simple way to create files.
Taken the post mentioned above:
String path = "C:"+File.separator+"hello"+File.separator+"hi.txt";
//(use relative path for Unix systems)
File f = new File(path);
//(works for both Windows and Linux)
f.mkdirs();
f.createNewFile();
try regex
fileName = fileName.replaceAll("\\d", "");

How to get to a file by passing relative path in java?

I am trying to understand "How to get to file by passing relative path of a file or folder?" . Here is the example:
CODE:
public class somex {
public static void main {
String fileName = System.getProperty("user.dir"); <---This gives me path for the current working directory.
File file = new File(fileName + "../../xml_tutorial/sample.xlsx" );
System.out.println(file.getCanonicalPath()); <---This gives me path for the file that is residing in folder called "xml_tutorial".
}
}
>>>>
Here, I know the file location so i was able to pass correct relative path. And, managed to print the file path. I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?
Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ? (NOTE: this is when the file exist and one hundred precent sure there is only one file with the name "sample.xlsx")
I have deleted the "sample.xlsx" and executed the above code; With no failing it gives me the path name and it is same path as when the file exists (i.e. before deleting). How it is possible ? I am expecting EXCEPTION here. why it is not throwing exception ?
File doesn't care whether the file actually exists. It just resolves the path. There's no need for the file to exist in order to take the path
/home/tjc/a/b/c/../../file.txt
...and turn it into the canonical form
/home/tjc/a/file.txt
If you want to know whether the file on that path actually exists, you can use the exists() method.
On your second, unrelated question:
Two, I want to use regular expression for the file name, such as: "../../xml_tutorial/samp.*". But this doesn't do the job and it gives me IOException. Why it is not able to identify the file sample.xlsx ?
There's nothing in the File documentation saying that it supports wildcards. If you want to do searches, you'll want to use list(FilenameFilter) or listFiles(FilenameFilter) and a FilenameFilter implementation, or listFiles(FileFilter) and a FileFilter implementation.

Java fails in moving (renaming) a file when the resulting file is on another filesystem

A program we have erred when trying to move files from one directory to another. After much debugging I located the error by writing a small utility program that just moves a file from one directory to another (code below). It turns out that while moving files around on the local filesystem works fine, trying to move a file to another filesystem fails.
Why is this? The question might be platform specific - we are running Linux on ext3, if that matters.
And the second question; should I have been using something else than the renameTo() method of the File class? It seems as if this just works on local filesystems.
Tests (run as root):
touch /tmp/test/afile
java FileMover /tmp/test/afile /root/
The file move was successful
touch /tmp/test/afile
java FileMover /tmp/test/afile /some_other_disk/
The file move was erroneous
Code:
import java.io.File;
public class FileMover {
public static void main(String arguments[] ) throws Exception {
boolean success;
File file = new File(arguments[0]);
File destinationDir = new File(arguments[1]);
File destinationFile = new File(destinationDir,file.getName() );
success = file.renameTo(destinationFile);
System.out.println("The file move was " + (success?"successful":"erroneous"));
}
}
Java 7 and above
Use Files.move(Path source, Path target, CopyOption... opts).
Note that you must not provide the ATOMIC_MOVE option when moving files between file systems.
Java 6 and below
From the docs of File.renameTo:
[...] The rename operation might not be able to move a file from one filesystem to another [...]
The obvious workaround would be to copy the file "manually" by opening a new file, write the content to the file, and delete the old file.
You could also try the FileUtils.moveFile method from Apache Commons.
Javadoc to the rescue:
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a
file in a platform independent manner.
From the docs:
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
If you want to move file between different file system you can use Apache's moveFile
your ider is error
beause /some_other_disk/ is relative url but completely url ,can not find the url
i have example
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt D:\Eclipse33_workspace_j2ee\test\src
The file move was successful
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt \Eclipse33_workspace_j2ee\test\src
The file move was erronous
result is url is error

Categories

Resources