【发布时间】:2015-05-07 15:55:55
【问题描述】:
我有以下代码在文件上写入字符串(加载的相对路径):
void writeFile(String string){
try {
//ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoader classLoader = getClass().getClassLoader();
File newFile = new File(classLoader.getResource("conf/passwords.txt").getFile());
//Path of "passwords.txt" where it writes the info
System.out.println("ABSOLUTE PATH: " +newFile.getAbsolutePath());
FileWriter flux = new FileWriter(newFile);
BufferedWriter writer = new BufferedWriter (flux);
writer.write(string);
writer.close();
} catch (IOException e) {
System.out.println("ERROR on file writing.\n" +e.getMessage());
e.printStackTrace();
}
}
它可以工作,但字符串没有写在我位于项目路径上的原始文件中,如下所示:src/conf/passwords.txt
而不是这个,字符串保存在以下路径中:C:\Users\becario01\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\searchLef\WEB-INF\classes \conf\passwords.txt
我想在我的原始文件中写入字符串,以便在我处理工作区时轻松显示。
我会非常感谢任何有用的回复。
问候。
【问题讨论】:
-
好吧,您自己发现了问题:您应该提供完整路径,因为“根”文件夹指向输出
/classes文件夹。 -
你选择的方法,通过
ClassLoader.getResource()方法,应该注意的是,如果你在“爆炸战争”的情况下这样做会起作用,但如果WAR 在部署时不会爆炸。如果你使用的是 Tomcat(我猜你是,但可能是错的),你应该相对于环境变量catalina.base而不是相对于ClassLoader。