java 我如何获取某些java包中的文件路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1116891/
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
How can i Get file path in some java package?
提问by Ibrahim AKGUN
i am new at java so maybe this will be a silly question. I got a file in my jasper.deneme package. I wanna give a full path for it.As ya see in picture i write it like
我是 Java 新手,所以也许这将是一个愚蠢的问题。我的 jasper.deneme 包中有一个文件。我想给它一个完整的路径。正如你在图片中看到的那样,我把它写成
string fullpath = "/jasper.deneme/reportDeneme.jasper";
but it does not workin :)
但它不起作用:)
so how can i get this file's path?
那么我怎样才能得到这个文件的路径呢?
回答by Michael Borgwardt
denemeJasper.class.getResource("reportDeneme.jasper").getPath()
denemeJasper.class.getResource("reportDeneme.jasper").getPath()
If you need the path for reading the file's contents, it would be simpler (and safer) to use getResourceAsStream()and avoid having to deal with paths entirely.
如果您需要读取文件内容的路径,则使用起来会更简单(也更安全),getResourceAsStream()并且不必完全处理路径。
BTW, your class denemeJasperviolates ubiquitous Java naming standards; as a class, its name should start with an uppercase letter.
顺便说一句,您的类denemeJasper违反了无处不在的 Java 命名标准;作为一个类,它的名字应该以大写字母开头。
回答by Tom Hawtin - tackline
The might be better off with a relative path, but the absolute path would be:
使用相对路径可能会更好,但绝对路径将是:
String fullpath = "/jasper/deneme/reportDeneme.jasper";
'/'replaces '.'in the package name whether the resource is located in a file, a jar or by any other means.
'/''.'无论资源位于文件、jar 还是任何其他方式,都在包名称中替换。

