【问题标题】:how to provide relative path in eclipse while running in tomcat server在tomcat服务器中运行时如何在eclipse中提供相对路径
【发布时间】:2018-11-27 04:39:15
【问题描述】:

我使用 REST 编写了 java 代码,它从保存的文件中检索员工详细信息,例如 id 和 name。绝对路径在运行 tomcat 服务器时工作正常,但是一旦我提供相对路径 tomcat 就找不到文件路径。我正在使用 BufferedReader 从文件中读取数据。

【问题讨论】:

  • 您介意提供必要的技术细节而不是理论上的细节吗?
  • 请分享项目结构
  • public class UserDao { private static final String path = "./resources/list.txt"; // 返回文件中的所有记录 public List getUser(String id) { List userList = new ArrayList();文件文件 = 新文件(路径);字符串读取线;尝试 (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { while ((readLine = bufferedReader.readLine()) != null) { User user = new User(Integer.valueOf(split[0]), split[ 1]); userList.add(user); } } } }
  • @michealjackson list.txt 文件是否保存在您的项目目录中?请显示您的项目结构和 list.txt 文件路径。
  • 大家好,感谢您的帮助!我解决了它像 String path = this.getClass().getClassLoader().getResource("./resources/list.txt").getPath(); String fullpath=fullPath = URLDecoder.decode(path, "UTF-8");

标签: java tomcat


【解决方案1】:

Eclipse 服务器插件会将 java 源代码编译成二进制类文件并将其放入work 目录,因此相对路径将不起作用。使其工作的最快方法是将文件放入源目录。然后 Eclipse 服务器插件会将该文件复制到您工作目录中的 classes 文件夹中。然后就可以使用相对路径来读取了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多