javaweb(实用)-IDEA下resources目录下txt文件读取写入引发的项目后台路径问题总结
首先idea下 真实路径与项目原本路径对比:
(文件操作之后idea内打开项目内的文件并没有任何变化,项目真实路径或者说编译后情况下的文件发生了变化)
项目中resources文件file.txt原本路径:
D:\java\IDEAProjects\springDemo\firstWeb\resources\prop\file.txt(windows资源管理器的直接复制过来的目录)
项目中真实resources文件file.txt的路径:(因为配了输出的位置在classes文件夹下)
所以是:D:/java/IDEAProjects/springDemo/firstWeb/web/WEB-INF/classes/prop/file.txt
获得resources的文件路径:
String path = this.getClass().getClassLoader().getResource("./prop/file.txt").getPath();
输出path是:/D:/java/IDEAProjects/springDemo/firstWeb/web/WEB-INF/classes/prop/file.txt最前面会带一个“/”
左斜杠右斜杠问题请移步->https://blog.csdn.net/zlwzlwzlw/article/details/7768313/
文件的操作
经过尝试一下四种路径都可以实现写入,读取想必也可以
测试代码:
@Test
public void readTest(){
String path = this.getClass().getClassLoader().getResource("./prop/file.txt").getPath();//"./prop/file.txt"效果一样
System.out.println(path);
System.out.println("---------------------------------------------------------------");
path = path.substring(1);
System.out.println(path);
System.out.println("--------------------------------------------------------------");
path = path.replaceAll("/", "\\\\");
System.out.println(path);
System.out.println("--------------------------------------------------------------");
path = path.replaceAll("\\\\", "\\\\\\\\");
System.out.println(path);
Date date = new Date();
String key = date.toString();
try {
FileOutputStream fos = new FileOutputStream(new File(path));
fos.write(key.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
小测试(写文件,也试试FileWriter)
直接相对路径写入根目录好像是会出现问题的
(下图注释的内容)
// 测试写入目录
String root = people.getClass().getResource("/").getPath();
//File file = new File( "/key");
File file = new File( root + "key");
if (!file.exists()) {
file.mkdir();
}
//File peoFile = new File("/key" + "/people.ser");
File peoFile = new File(root + "key" + "/people.ser");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileWriter fw = new FileWriter(peoFile);
fw.write(1 + "\n1");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
会报权限问题permission denied,应该是不能写入到当前项目中?但是输出目录应该是可以的
这样通过路径写入就是可以写入的。
me的path:path:/Users/searlas/IdeaProjects/newLearningDemo/java/target/classes/
杂记
附上项目内获取绝对路径的方法:(应该是他人总结的 以前笔记本里面发现的,侵删)
1可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
例如 : E:\eclipseM9/workspace/tree/WEB-INF/classes/
这个方法也可以不在web环境里确定路径,比较好用
3.request.getContextPath(); 是在开发Web项目时,经常用到的方法,是为了解决相对路径的问题,可返回站点的根路径。
获得web根的上下文环境
如 /tree
tree是我的web项目的root context
/*jsp 取得当前目录的路径
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/
path=C:\jboss-4.0.5.GA\server\default\tmp\deploy\tmp14544test-exp.war\
String path = (String)request.getContextPath();