我的问题是getAbsolutePath
忽略了我想要查找的文件周围的某些文件夹。我要做的是仅使用其名称获取文件的文件路径。这是我正在使用的代码:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenFile {
public static void main(String[] args) throws IOException{
File file = new File("Point.java");
String path = file.getCanonicalPath();
try {
Desktop.getDesktop().open(new File(path));
} catch(IOException e) {
System.out.println("not work");
}
}
}
我收到了这个错误:
Exception in thread "main" java.lang.IllegalArgumentException: The file: /Users/default/Desktop/Eclipse/TreeThing/Point.java doesn't exist.
at java.awt.Desktop.checkFileValidation(Desktop.java:210)
at java.awt.Desktop.open(Desktop.java:270)
at ForkBomb.main(ForkBomb.java:11)
真正的文件路径是/Users/default/Desktop/Eclipse/TreeThing/src/Point.java
,但由于目录src被忽略,程序将无法运行。我该如何解决?
答案 0 :(得分:1)
您似乎正在从/ Users / default / Desktop / Eclipse / TreeThing目录运行代码。这将为您的应用程序设置“当前工作目录”。
因此,当您在没有路径的情况下实例化File
对象时,代码会假定它位于当前工作目录中。
不执行搜索。
如果要引用现有的Point.java,请使用:
File file = new File("src/Point.java");
......或:
File file = new File("/Users/default/Desktop/Eclipse/TreeThing/src/Point.java");