1、在Java开发工具的project中使用相对路径
在project中,相对路径的根目录是project的根文件夹,在此就是repathtest文件夹了。
创建文件的写法是:
[Java] 纯文本查看 复制代码
?
1 | |
[Java] 纯文本查看 复制代码
?
1 | |
注意:
路径不以“/”开头;
脱离了IDE环境,这个写法就是错误的,也并非每个IDE都如此,但我见到的都是这样的。
2、通过CLASSPATH读取包内文件
读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流:
[Java] 纯文本查看 复制代码
?
1 | |
有了字节流,就能读取到文件内容了。
注意:
这里必须以“/”开头;
3、看看完整的测试代码:
[Java] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
运行结果:
[Java] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 |
|
这是通过IDEA开发工具运行的,结果没问题,如果换成控制台执行,那么使用了项目相对路径的读取方式会失败,原因是,此时已经脱离了项目的开发环境,-----这个问题常常困扰着一些人,代码在开发工具好好的,发布后执行就失败了!
5、获取CLASSPATH下文件的绝对路径
当使用相对路径写入文件时候,就需要用到绝对路径。下面是个例子:
[Java] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
输出:
[Java] 纯文本查看 复制代码
?
1 2 3 4 5 |
|
总结
使用工程相对路径是靠不住的。
使用CLASSPATH路径是可靠的。
对于程序要读取的文件,尽可能放到CLASSPATH下,这样就能保证在开发和发布时候均正常读取