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.
Related
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 the difference between the following two methods for creating a file?
new File(System.getProperty("user.dir"));
new File("");
Java identifies the first one as a directory, and the second one's neither a file nor a directory! Why is that the case?
Code:
public class MainClass {
public static void main(String[] args) throws Exception {
System.out.println("File Created with CurrentDir taken From System Props");
File f1 = new File(System.getProperty("user.dir"));
System.out.println("Absolute Path: " + f1.getAbsolutePath());
System.out.println("isDirectory: " + f1.isDirectory());
System.out.println("isFile: " + f1.isFile());
System.out.println();
System.out.println("File Created with Empty String Path");
File f2 = new File("");
System.out.println("Absolute Path: " + f2.getAbsolutePath());
System.out.println("isdirectory: " + f2.isDirectory());
System.out.println("isFile: " + f2.isFile());
}
}
Output:
File Created with CurrentDir taken From System Props
Absolute Path: D:\Java Workspace\my_Workspace\JavaTest
isDirectory: true
isFile: false
File Created with Empty String Path
Absolute Path: D:\Java Workspace\my_Workspace\JavaTest
isdirectory: false
isFile: false
Explanation
It may seem a little non-intuitive but actually that's just how the class is supposed to work according to its documentation. It's called empty abstract pathname in the documentation:
The empty abstract pathname has no prefix and an empty name sequence.
And from your constructor File#File(String):
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
So the File class actually interprets the empty name as actual name. When you test File#isDirectory() or File#isFile() it thus checks if there exists a file or directory like
D:\Java Workspace\iTAW_Workspace\JavaTest\<empty>
Note the <empty> which I wrote to indicate that it actually searches for a file here with the empty name. Obviously such a file can not exist, thus the result will always be false. So again, it does not check
D:\Java Workspace\iTAW_Workspace\JavaTest\
but rather the empty file in this directory, which does not exist.
Unfortunately you don't see this when using the File#toAbsolutePath() method as there is no representation for an empty name.
NIO
Note that the class File and everything related to it is outdated. Nowadays file IO is done using NIO revolving around Files, Paths and Path. This API is much more cleaner and more intuitive. It will also work as intended on your current example:
Files.isDirectory(Paths.get("")); // true
Take a look at the documentation for more.
Creating a file with empty string results to creating a File instance which actually does not exist and its absolute pathname is "empty abstract pathname".
-> That's why the second one's neither a file nor a directory for you.
The reason behind that, a maybe little bit confusing output for you, is definition located in javadocs:
If this abstract pathname is the empty abstract pathname then the
pathname string of the current user directory, which is named by the
system property user.dir, is returned.
You can find more about this topic here
https://docs.oracle.com/javase/6/docs/api/java/io/File.html
You need to make the difference between the Java object File and a file actually present on your computer.
In the first case : new File(System.getProperty("user.dir")). You create a Java object File and give him a path : System.getProperty("user.dir"). Later when you call the function .getAbsolutePath() it returns you the path you gave. Then when you call .isDirectory() it tells you true because there is a directory corresponding to this Java object File.
In the second case, new File("") it creates a Java object File and you give it a path : "". Since the path given is not absolute, the system will resolve it as a relative from the user.dir path.
from documentation
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.
Later when you call the function .getAbsolutePath() it returns you the path you gave, so the path to user dir + empty string : D:\Java Workspace\iTAW_Workspace\JavaTest\<empty>. Then when you call .isDirectory() it tells you false because there is no directory corresponding to this path. (same reason for isFile())
new File("") creates new file with relative (empty) path. As this file doesn't exist both isDirectory() and isFile() return false (corresponds to javadoc).
From javadoc
boolean java.io.File.isDirectory()
...
Returns: true if and only if
the file denoted by this abstract pathname exists and is a directory;
false otherwise
The same is true for isFile(). and as long as your file doesn't exist both methods return false.
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.
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
I have the following code in a static class called Methods that is archived in a jar:
System.out.println(Methods.class.getResource("tagdict.txt")); // 1
URL test = Methods.class.getResource("tagdict.txt"); // 2
System.out.println(test.getPath()); // 3
TagDictionary dict = new POSDictionary(test.getPath()); // 4
The first System.out (1) says:
rsrc:de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
The second System.out (2) says:
de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt
Line 4 throws a
java.io.FileNotFoundException: de/fhg/scai/bio/harsha/classificationworkflow/tagdict.txt (No such file or directory)
The file tagdict.txt is placed in the same package as the Method.class, which is de/fhg/scai/bio/harsha/classificationworkflow.
I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.
Line 3 just prints out the path component of the URL returned by getResource. It doesn't actually check if that path represents a real file on disk.
It looks like the POSDictionary constructor is trying to create a File using the path string passed to it, and this path doesn't actually represent an on-disk file, therefore throwing the exception.
I do not understand why line 4 throws a FileNotFoundException even though the file was found already inside the jar.
Because if the resource is in a JAR, then it's not a file. Such resources can only be accessed by opening input streams directly from the URL object, or by using getResourceAsStream() instead of getResource(). They can't be accessed using java.io.File, since they're not actual disk files.