Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Google应用程序引擎-读取Java中的静态文件_Java_Google App Engine_File Io - Fatal编程技术网

Google应用程序引擎-读取Java中的静态文件

Google应用程序引擎-读取Java中的静态文件,java,google-app-engine,file-io,Java,Google App Engine,File Io,我有一个AppEngineServlet,它基于JSON文件(存储在WEB-INF下的“Resources”文件夹中)创建对象。我在一个单独的类中处理文件的解析: public class EventParser { static Gson gson = new Gson(); static String fileName = "/SOServices-war/src/main/webapp/WEB-INF/Resources/mockEvents.json"; stat

我有一个AppEngineServlet,它基于JSON文件(存储在WEB-INF下的“Resources”文件夹中)创建对象。我在一个单独的类中处理文件的解析:

public class EventParser
{
    static Gson gson = new Gson();
    static String fileName = "/SOServices-war/src/main/webapp/WEB-INF/Resources/mockEvents.json";
    static File file = new File(fileName);

    public static List<Event> readDataFromJSON() throws IOException
    {
        InputStreamReader inReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
        String stringFromRes = null;
        try (BufferedReader br = new BufferedReader(inReader))
        {
            StringBuilder sb = new StringBuilder();
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null)
            {
                sb.append(sCurrentLine);
                sb.append(System.lineSeparator());
            }

            stringFromRes = sb.toString();

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        List<Event> events = new ArrayList<Event>();
        Type listOfTestObject = new TypeToken<List<Event>>(){}.getType();
        events = gson.fromJson(stringFromRes, listOfTestObject);

        return events;
    }
}

这就解决了我的问题。

我不确定是否可能重复。我不是在任何servlet中进行解析,而是在一个单独的类中进行解析。同样在以前的项目设置中(使用eclipse+应用程序引擎插件),我能够阅读war/WEB-INF资源,正如我所写的,我认为现在情况有所不同。您不应该假设war文件在文件系统上被分解。考虑将这些资源添加到类路径中。我设法通过将servlet上下文从servlet传递到解析方法并使用GealRealPalthFor来解决这个问题,这类似于链接问题中的解决方案。谢谢你的建议,我会很快用答案更新我的问题。
List<Event> events = EventParser.readDataFromJSON(this.getServletContext());
String filePath =  context.getRealPath(fileName);
InputStreamReader inReader = new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8");