简体   繁体   English

Java:文件相对路径 - 未找到文件

[英]Java: File relative path - No File Found

I coding a java send mail program which attach a test report file at relative path.我编写了一个 java 发送邮件程序,它在相对路径中附加了一个测试报告文件。

Questions: How to setup the path so that the file can be found?问题: 如何设置路径以便找到文件?

Test Report Directory:测试报告目录:

com.securister\report\Test-Report.html com.securister\report\Test-Report.html

Java File: Java 文件:

com.securister\src\test\java\com\securister\TestManager com.securister\src\test\java\com\securister\TestManager

I tried setup like我试过像这样的设置

String filename = "\..\..\..\..\..\..\report\Test-Report.html"字符串文件名 = "\..\..\..\..\..\..\report\Test-Report.html"

but end up no file found.但最终没有找到文件。

Should i using classpath?我应该使用类路径吗?

You have the structure of src/main/resources and src/test/resources , put the你有src/main/resourcessrc/test/resources的结构,把

target file under the resource in a test as I guess我猜想在测试中的资源下的目标文件

, And read the file from the path src/test/resources/report/Test-Report.html ,并从路径src/test/resources/report/Test-Report.html读取文件

You can print the current directory of your java program where it is executed from with this java code,您可以使用此 java 代码打印 java 程序的当前目录,

System.out.println("CurrentDir: " + (new File(".").getCanonicalPath()));

Say it prints,说它打印,

CurrentDir: D:\XXX\workspace\test Then you can correctly choose a path through which your file can be correctly located. CurrentDir: D:\XXX\workspace\test那么你就可以正确的选择一个路径,通过这个路径你的文件可以被正确定位。

Most likely, your src folder should be in the test directory and in that case you can either move your file from src folder to test folder or refer your file in your code like this,最有可能的是,您的 src 文件夹应该位于测试目录中,在这种情况下,您可以将文件从 src 文件夹移动到测试文件夹,或者像这样在代码中引用您的文件,

..\Test-Report.html ..\测试报告.html

which should be able to read your file.它应该能够读取您的文件。

Let me know if this works.让我知道这个是否奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM