Java 获取当前文件的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19451480/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:18:14  来源:igfitidea点击:

Get Path of current file

java

提问by sportsfan72

How do I get the directory where the a .java file is located? I don't want to use System.getProperty("user.dir"), because that gives me the directory of the executable, and not the directory of the .java file that contains this line of code.

如何获取 .java 文件所在的目录?我不想使用System.getProperty("user.dir"),因为它给了我可执行文件的目录,而不是包含这行代码的 .java 文件的目录。

I need this because I'm developing a JSP web-app, and the Java code creates a .csv file on the server side and I want to make it available on the client side, but I would need to place the csv file where the location of the .html files are so that they could be downloaded.

我需要这个,因为我正在开发一个 JSP web 应用程序,Java 代码在服务器端创建了一个 .csv 文件,我想让它在客户端可用,但我需要将 csv 文件放在.html 文件的位置是可以下载的。

My current folder structure is like:

我当前的文件夹结构是这样的:

Java Resources ->src
->.java file

Java 资源 ->src
->.java 文件

WebContent
->.html file

WebContent
->.html 文件

采纳答案by RamonBoza

Try this for asking for your class

试试这个来询问你的课程

String s = getClass().getName();
int i = s.lastIndexOf(".");
if(i > -1) s = s.substring(i + 1);
s = s + ".class";
System.out.println("name " +s);
Object testPath = this.getClass().getResource(s);
System.out.println(testPath);

this code snippet is from this.getClass().getResource("").getPath() returns an incorrect path

此代码片段来自this.getClass().getResource("").getPath() 返回不正确的路径

回答by RamonBoza

The source file might as well not exist. Java is a compiled language, it runs compiled files, .java files aren't necessary and thus might not be there at runtime.

源文件也可能不存在。Java 是一种编译语言,它运行编译文件,.java 文件不是必需的,因此在运行时可能不存在。

You can however, get the location of the .class file, as it was previously suggested.

但是,您可以按照之前的建议获取 .class 文件的位置。