如何获取JAVA项目中的文件绝对路径 [英] How to get the file absolute path in JAVA project
问题描述
您好我需要使用FileInputStream来读取文件,但我没有找到正确的路径。我的文件位于C:\ Users \tester \Documents \ Java Project \Samples \ProjectOne \src \ pdfReader
但是当我使用下面的代码时,我得到了错误的路径是
/C:/Users/tester/Documents/Java%20Project/Samples/ProjectOne/bin/ProjectOne/TestFile.txt
Hi I need to read the file by using FileInputStream but I didn't get the right path. My file is location at C:\Users\tester\Documents\Java Project\Samples\ProjectOne\src\pdfReader However when I used the below code, I get the wrong path that is "/C:/Users/tester/Documents/Java%20Project/Samples/ProjectOne/bin/ProjectOne/TestFile.txt"
有我的代码:
String filePath;
filePath=MainForm.class.getResource("TestFile.txt").getPath();
有人会告诉我如何获取文件路径吗?
Would someone tell me how to get the file path?
推荐答案
您可能正在使用Eclipse,因为您在源文件夹中保存了文件 TestFile.txt
复制到 bin
文件夹,即项目的输出文件夹。因此,路径没有错。在您的代码中使用 getResource
方法,该文件将从您的 MainForm.class
所在的同一目录中检索发现。
You are probably using Eclipse and as you have saved the file TestFile.txt
inside your source folder it is being copied to the bin
folder, the output folder of your project. Therefore, the path is not wrong. As in your code you use getResource
method, the file will be retrieved from the same directory where your MainForm.class
was found.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)
如果你真的想从源文件夹中获取这样的文件,那么你应该这样做:
If you really want to get such file from your source folder, then you should do something like this:
System.out.println(new File("src/pdfReader/TestFile.txt").getAbsolutePath());
但是,如果您打算分发您的应用程序,最好将此类文件存储在一个资源
文件夹,因为源文件夹通常不包含在 dist
包中。
However, if you are planning to distribute your application it would be better to store this kind of file in a resources
folder because source folders are usually not included in dist
packages.
这篇关于如何获取JAVA项目中的文件绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!