Java无法获取当前目录中存在的文件的路径
如果文件存在于运行 Java 应用程序的同一目录中,并且我为该文件创建了一个 File 对象,则文件路径的 Java File 方法也包含文件名。代码和输出如下。
如果这是我正在使用的 JDK 版本中的一个错误,那么现在肯定有人会看到它。
为什么 File.getAbsolutePath() 和 File.getCanonicalPath() 包含文件名? Javadocs 指示应返回目录名称。
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();
}
}
}
这是输出:
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
到目前为止,我发现在这种情况下获取目录的唯一方法是手动解析文件名。
在这种情况下,File 类是否有办法获取目录名称(在不指定目录的情况下创建当前目录中存在的文件)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,他们没有。如果您愿意指出您认为他们这样做的原因,那么有人可能会指出您推理中的错误。此外,如果您在给定某些特定输入的情况下准确指定您希望看到的输出内容,我们也可以为您提供帮助。您的问题标题似乎也很奇怪,因为您的问题似乎是它返回文件的完整路径。
编辑:我想我理解你困惑的根源。 File 以与平台无关的方式表示文件系统路径。它可以是文件或目录的路径。它也始终代表相同的路径,尽管不一定是相同的绝对路径。这是一个非常细微但非常重要的区别。表示相对路径的 File 对象始终是相对的。给定一个代表相对路径的 File,您可以使用 getAbsolutePath() 获取当前对应的绝对路径。然而,这并没有改变文件代表相对路径的事实。对同一 File 对象进一步调用 getAbsolutePath() 可能会返回不同的值。例如,考虑一下:
现在应该清楚,文件代表的路径只是:路径。此外,路径可以由零个或多个部分组成,并且在任何文件上调用 getParent() 都会返回该文件的路径,并删除最后一个路径元素,除非没有要删除的“最后一个路径元素”。因此,
new File("foo").getParent()
的预期结果是null
,因为相对路径“foo”没有父路径。从上面的示例和解释中,您应该能够看到,在创建相对路径 File 对象时获取包含目录的方法是需要
注意的,“绝对路径”取决于您当时的环境。
附加说明:由于文件是可序列化的,因此您可以将相对路径文件写入磁盘或通过网络发送它。该文件在另一个 JVM 中反序列化时,仍将表示相对路径,并将根据该 JVM 的当前工作目录进行解析。
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:
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()
isnull
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
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.
该行为是预期的。 文档确实更不用说不包括文件名。
也许您对
getAbsolutePath()
和getAbsoluteFile()
之间的区别感到困惑。后者返回一个 File 实例。The behaviour is expected. The documentation does not mention that the filename is not included.
Perhaps you are confused by the difference between
getAbsolutePath()
andgetAbsoluteFile()
. It's that the latter returns aFile
instance.我不知道为什么你认为 Javadoc 说它返回目录名称。
这是 Javadoc——
文件和目录路径名的抽象表示。
用户界面和操作系统使用与系统相关的路径名字符串来命名文件和目录。此类提供了分层路径名的抽象的、独立于系统的视图。抽象路径名有两个组成部分:
抽象路径名中的第一个名称可以是目录名,或者对于 Microsoft Windows UNC 路径名,可以是主机名。 抽象路径名中的每个后续名称都表示一个目录;姓氏可以表示目录或文件。 空抽象路径名没有前缀和空名称序列。
http://download.oracle .com/javase/6/docs/api/java/io/File.html#getAbsolutePath%28%29
返回此抽象路径名的绝对路径名字符串。
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:
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.
除了有关
getAbsolutePath
和getCanonicalPath
的现有答案之外,还请注意,File.getParent()
并不意味着“父目录” " 它仅指用于创建文件的父文件对象。例如,如果文件对象可以这样创建:
f1
将引用/path/to/a/directory/x.txt
,它的父级是dir
(/path/to/a/directory
)f2
将引用/path/to/a/directory/../another/ y.txt
,它是规范路径将是/path/to/a/another/y.txt
,但它的父级仍然是对dir
的引用(/path/to/a/directory
)f3
将引用当前目录中的z.txt
。它没有父文件对象,因此f3.getParent()
或f3.getParentFile()
将返回 null。In addition to the existing answers with regards to
getAbsolutePath
andgetCanonicalPath
, please also note, thatFile.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:
f1
would refer to/path/to/a/directory/x.txt
, it's parent isdir
(/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 todir
(/path/to/a/directory
)f3
would refer toz.txt
in the current directory. It does not have a parent file object, sof3.getParent()
orf3.getParentFile()
would return null.path 是完整路径
如果您只想要需要调用 file.getParent() 的目录,则
path is the full path
if you only want the directory you need to call file.getParent()