java项目相对路径问题

来源:互联网 发布:怎么做淘宝客服怎么找 编辑:程序博客网 时间:2024/04/20 05:57

首先设定项目路径为 D:/java/workplaces/poj_test/              poj_test 为项目名


包结构
poj_test
                 -src
                        -com
                                classA
                               classB
                       -resource
                              msg.wav
                -bin
                      -com
                              classA
                              classB
                      -resource
                             msg.wav
                -res
                      msg.wav


一:使用file


 1:最前面不加“/” 代表起始路径为 项目根路径
例:File file = new File("resource/msg.wav"); 路径为D:/java/workplaces/poj_test/resource/msg.wav 

   正确为File file = new File("src/resouse/msg.wav")


 2:最前面加 “/” 代表起始路径为 磁盘根路径
例:File file = new File("resource/msg.wav"); 路径为D:/resource/msg.wav


二:使用 this.getClass().getResource 时


 1:最前面加“/” 代表起始路径为 bin文件夹(即classpath 路径)

例 在classA中 使用this.getClass().getResource("/resource/msg.wav"); 时 路径为 D:/java/workplaces/poj_test/bin/resource/msg.wav


 2:最前面不加“/” 代表起始路径为 当前类所在的文件夹
例 在classA中 使用this.getClass().getResource("resource/msg.wav"); 时 路径为 D:/java/workplaces/poj_test/bin/com/resource/msg.wav
正确为 this.getClass().getResource("/resource/msg.wav")


注意this.getClass().getResource 只能访问bin文件下的文件 (例如不能访问res文件夹)
1 0
原创粉丝点击