从项目文件夹java获取文件
我想通过使用“文件类”从项目文件夹中获取文件,我该怎么做?
File file=new File("x1.txt");
好吧,有许多不同的方法可以用Java获取文件,但这是一般的要点。
不要忘记你至少需要在try {} catch (Exception e){}
中包含它,因为File是java.io
一部分,这意味着它必须有try-catch块。
不要踩到Ericson的问题,但如果您使用的是实际的软件包,那么除非您明确使用它的位置,否则您将遇到文件位置的问题。 相对路径与Packages混乱。
即
src/ main.java x.txt
在这个例子中,使用File f = new File("x.txt");
在main.java
中将抛出一个未找到文件的exception。
但是,使用File f = new File("src/x.txt");
将工作。
希望有所帮助!
这听起来就像文件嵌入在您的应用程序中。
你应该使用getClass().getResource("/path/to/your/resource.txt")
,它返回一个URL
或getClass().getResourceAsStream("/path/to/your/resource.txt");
如果它不是嵌入式资源,那么您需要知道从应用程序的执行上下文到文件所在位置的相对路径
如果你没有指定任何路径并只放置文件(就像你做的那样),默认目录始终是你的项目之一(它不在“src”文件夹中。它就在你项目的文件夹里面)。
如果您尝试加载的文件与Java类不在同一目录中,则必须使用运行时目录结构而不是设计时出现的结构。
要找出运行时目录结构是什么,请检查{root project dir} / target / classes目录。 该目录可通过“。”访问。 URL。
根据user4284592的回答,以下内容对我有用:
ClassLoader cl = getClass().getClassLoader(); File file = new File(cl.getResource("./docs/doc.pdf").getFile());
具有以下目录结构:
{root dir}/target/classes/docs/doc.pdf
希望这有助于任何努力理解URL逻辑的人。
这些线在我的情况下工作,
ClassLoader classLoader = getClass().getClassLoader(); File fi = new File(classLoader.getResource("test.txt").getFile());
在src中提供了test.txt文件
在javaFx 8中
javafx.scene.image.Image img = new javafx.scene.image.Image("/myPic.jpg", true); URL url = new URL(img.impl_getUrl());
给出test/resources
的文件application.yaml
ll src/test/resources/ total 6 drwxrwx--- 1 root vboxsf 4096 Oct 6 12:23 ./ drwxrwx--- 1 root vboxsf 0 Sep 29 17:05 ../ -rwxrwx--- 1 root vboxsf 142 Sep 22 23:59 application.properties* -rwxrwx--- 1 root vboxsf 78 Oct 6 12:23 application.yaml* -rwxrwx--- 1 root vboxsf 0 Sep 22 17:31 db.properties* -rwxrwx--- 1 root vboxsf 618 Sep 22 23:54 log4j2.json*
从测试上下文中,我可以获取该文件
String file = getClass().getClassLoader().getResource("application.yaml").getPath();
这实际上将指向test-classes
的文件
ll target/test-classes/ total 10 drwxrwx--- 1 root vboxsf 4096 Oct 6 18:49 ./ drwxrwx--- 1 root vboxsf 4096 Oct 6 18:32 ../ -rwxrwx--- 1 root vboxsf 142 Oct 6 17:35 application.properties* -rwxrwx--- 1 root vboxsf 78 Oct 6 17:35 application.yaml* drwxrwx--- 1 root vboxsf 0 Oct 6 18:50 com/ -rwxrwx--- 1 root vboxsf 0 Oct 6 17:35 db.properties* -rwxrwx--- 1 root vboxsf 618 Oct 6 17:35 log4j2.json*
刚做了一个快速的谷歌搜索,发现了
System.getProperty("user.dir");
以String的forms返回当前工作目录。 所以要获得一个文件,只需使用
File projectDir = new File(System.getProperty("user.dir"));
String path = System.getProperty("user.dir")+"/config.xml"; File f=new File(path);