在开发Google App Engine应用程序时,无法使用本地测试中的相对路径访问文件

时间:2017-04-25 19:01:39

标签: java eclipse file google-app-engine gcloud

我正在尝试在Google Cloud Platform上编写和部署一个简单的网络应用程序。我在Mac上的Eclipse上安装了gcloud和相应的库/插件。我使用以下代码尝试打开HttpServeletRequest中指定的文件:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

    resp.setContentType("text/html");
    resp.getWriter().println("<p>DEBUG: In Create2.</p>");

    // get the file info
    // to get the value of each input, always use the name and then
    // req.getParameter(name);
    String fileName = req.getParameter("file");

    // create the file
    File file = new File(fileName);
    resp.getWriter().println("<p>"+file.getAbsolutePath()+"</p>");

    if (file.exists()) {
        ...
    }
    else  {
        ...
    }

我将test.txt文件放在project / src / main / webapp目录下,将此项目作为app引擎运行,并将“test.txt”提交给servelet。但是

在我的本地计算机(localhost:8080)中,file.exists()始终失败并且打印的绝对路径为

   Applications/Eclipse/Contents/MacOS/test.txt

相反,在我将项目部署到Google App Engine之后,一切正常并且打印的绝对路径是

  /base/data/home/apps/XXXX/20170425t133741.400812218449586767/test.txt

我读了几个讨论主题,都说GAE / Google Cloud Platform中的文件访问是相对路径。但是为什么我的eclipse会在尝试打开文件时将其解释为绝对路径?是否有解决此问题的方法,以便我可以始终在本地和谷歌云上使用相对路径?

非常感谢。

1 个答案:

答案 0 :(得分:2)

如果您可以正确设置本地App Engine开发服务器的工作目录,则在本地使用相对路径时不会遇到问题。不幸的是,截至目前,Cloud Tools for Eclipse插件并不支持更改工作目录。以下是您可以采取的解决方法:

  1. 运行本地开发服务器并检查控制台视图中的服务器日志,以查看服务器应用作工作目录的实际Web应用程序根目录。您将看到如下日志消息:

    WARNING: Your working directory, (<...your current, out-of-sync local server working directory...>) is not equal to your web application root (<...your workspace...>.metadata/.plugins/org.eclipse.wst.server.core/tmp0/<...your Eclipse project name...>)

  2. 打开服务器视图。停止服务器。

  3. 双击服务器。在弹出的概述页面上单击打开启动配置
  4. 选择参数标签。
  5. -Duser.dir=<...the directory of the web application root from the server log...>框中输入VM arguments:。单击确定。 (不幸的是,下面的工作目录部分并不起作用。)
  6. 从现在开始,您不会看到WARNING消息,服务器将使用您提供的目录作为工作目录。

    更新:这已在最近的CT4E版本中得到修复,它可以自动正确设置工作目录(除非您在单个本地服务器中运行多个项目)。如果遇到此问题,请更新到最新的CT4E。