java Java无法获取当前目录中存在的文件的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7153729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java can't get the path of a file that exists in the current directory
提问by Dean Schulze
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.
如果文件存在于运行 Java 应用程序的同一目录中,并且我为该文件创建了一个 File 对象,则文件路径的 Java File 方法也包括文件名。代码和输出如下。
If this was a bug in the JDK version I'm using someone would surely have seen it by now.
如果这是我正在使用的 JDK 版本中的错误,那么现在肯定有人会看到它。
Why do File.getAbsolutePath() and File.getCanonicalPath() include the file name? The Javadocs indicate that the directory name should be returned.
为什么 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();
}
}
}
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)?
在这种情况下,File 类是否有获取目录名称的方法(在不指定目录的情况下创建存在于当前目录中的 File)?
回答by Ryan Stewart
Why do File.getAbsolutePath() and File.getCanonicalPath() include the file name? The Javadocs indicate that the directory name should be returned.
为什么 File.getAbsolutePath() 和 File.getCanonicalPath() 包含文件名?Javadocs 指示应该返回目录名称。
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 isreturning the full path to a file.
不,他们没有。如果您愿意指出您认为他们这样做的原因,那么可能有人会指出您推理中的错误。此外,如果您在给定某些特定输入的情况下准确指定您希望看到的输出,我们也可以为您提供帮助。您的问题标题似乎也很奇怪,因为您的问题似乎是返回文件的完整路径。
Edit:I think I understand the source of your confusion. A Filerepresents 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 absolutepath. 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:
编辑:我想我明白你困惑的根源。一个文件代表在平台无关的方式的文件系统路径。它可以是文件或目录的路径。它也总是代表相同的路径,尽管不一定是相同的绝对路径。这是一个非常细微但非常重要的区别。表示相对路径的 File 对象始终是relative。给定一个表示相对路径的文件,您可以使用 getAbsolutePath() 获取当前对应的绝对路径。但是,这不会改变 File 表示相对路径的事实。在同一个 File 对象上进一步调用 getAbsolutePath() 可能会返回不同的值。考虑,例如:
// 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.
现在应该很清楚了,一个 File 代表的路径只是:一个路径。此外,路径可以由零个或多个部分组成,并且在任何文件上调用 getParent() 会返回该文件的路径,并删除最后一个路径元素,除非没有要删除的“最后一个路径元素”。因此预期的结果new File("foo").getParent()
是null
因为相对路径“foo”没有父路径。
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
从上面的示例和解释中,您应该能够看到创建相对路径 File 对象时获取包含目录的方法是
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.
附加说明:由于 File 是可序列化的,您可以将相对路径文件写入磁盘或通过网络发送。该文件在另一个 JVM 中反序列化时,仍将表示相对路径,并将根据该 JVM 的当前工作目录进行解析。
回答by Bozho
The behaviour is expected. The documentationdoes 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.
也许您对getAbsolutePath()
和之间的区别感到困惑getAbsoluteFile()
。就是后者返回一个File
实例。
回答by Kal
I'm not sure why you think the Javadoc says that it returns the directory name.
我不确定您为什么认为 Javadoc 说它返回目录名称。
Here is the Javadoc --
这是 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.
- 可选的系统相关前缀字符串,例如磁盘驱动器说明符、UNIX 根目录的“/”或 Microsoft Windows UNC 路径名的“\\”,以及
- 零个或多个字符串名称的序列。
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.
抽象路径名中的第一个名称可以是目录名,或者在 Microsoft Windows UNC 路径名的情况下是主机名。抽象路径名中的每个后续名称表示一个目录;姓氏可以表示目录或文件。空抽象路径名没有前缀和空名称序列。
http://download.oracle.com/javase/6/docs/api/java/io/File.html#getAbsolutePath%28%29
http://download.oracle.com/javase/6/docs/api/java/io/File.html#getAbsolutePath%28%29
Returns the absolute pathname string of this abstract pathname.
返回此抽象路径名的绝对路径名字符串。
回答by beny23
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.
除了关于getAbsolutePath
and的现有答案之外getCanonicalPath
,还请注意,这File.getParent()
并不意味着“父目录”,它仅指用于创建文件的父文件对象。
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
)
f1
指的是/path/to/a/directory/x.txt
,它的父级是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
)
f2
会引用/path/to/a/directory/../another/y.txt
,它的规范路径是/path/to/a/another/y.txt
,但它的父级仍然是对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.
f3
将z.txt
在当前目录中引用。它没有父文件对象,因此f3.getParent()
或f3.getParentFile()
将返回 null。
回答by ratchet freak
path is the full path
path 是完整路径
if you only want the directory you need to call file.getParent()
如果你只想要你需要调用的目录 file.getParent()