【问题标题】:Write a file in a "resources" folder within Eclipse source [duplicate]在 Eclipse 源代码的“资源”文件夹中写入文件 [重复]
【发布时间】: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 文件夹。
  • This 可能会帮助你,或者可能this
  • 你选择的方法,通过ClassLoader.getResource() 方法,应该注意的是,如果你在“爆炸战争”的情况下这样做会起作用,但如果WAR 在部署时不会爆炸。如果你使用的是 Tomcat(我猜你是,但可能是错的),你应该相对于环境变量 catalina.base 而不是相对于 ClassLoader

标签: java eclipse


【解决方案1】:

总而言之,您似乎在 Eclipse WST 下运行 Tomcat,您的 web 应用程序在某个时间点写出一个文件,并且您希望该文件出现在您的 Eclipse 项目源代码树中,您可以轻松地重新加载/查看它。在这种情况下,如您所见,使用类加载器获取文件的位置将导致它出现在 webapp 部署的运行时中,而不是出现在您的 Eclipse 项目源中。

您要做的是以某种方式将您的 Eclipse 项目位置传递给您的 webapp,然后使用该绝对路径打开您的 File。有很多方法可以做到这一点 - 一种简单的方法是更改​​ Eclipse Tomcat 启动以添加 JVM 属性,例如-Declipse.project.path=${workspace_loc}/searchLef,然后读取该系统属性并将其用作文件的基本路径,添加相对路径 src/conf/passwords.txt。手动刷新项目后,该文件将出现在源代码树中。

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    相关资源
    最近更新 更多