How do I read a file in App Engine?

2019-02-08 12:40发布

I have a file at /WEB-INF/config.txt on app engine. What is the path to the file on app engine?

eg: new File(/*What path do i put here?*/)

5条回答
戒情不戒烟
2楼-- · 2019-02-08 13:23

This worked for me:

servletContext.getResourceAsStream("/WEB-INF/config.txt")

查看更多
在下西门庆
3楼-- · 2019-02-08 13:23

In my case, I didn't have access to ServletContext - getServletContext():

This worked for me:

InputStream inputStream = new FileInputStream(new File("WEB-INF/config.txt"));
查看更多
叼着烟拽天下
4楼-- · 2019-02-08 13:32

I found this to be a good way to grab the entire file in a String:

import java.net.URL;
import java.io.File;
import java.io.FileInputStream;
import com.google.common.io.CharStreams;

URL resource = getServletContext().getResource("/WEB-INF/config.txt");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
String myString = CharStreams.toString(new InputStreamReader(input, "UTF-8"));
查看更多
放我归山
5楼-- · 2019-02-08 13:36

There's some documentation at appengine how to add resources to your project. Check out the <resource-files> part. Some further information can be read in the description of the appengine sandbox.

When the resources are added to your project you can use the following code to read their content:

File f = new File("path/below/my/project/directory/config.txt");
InputStream in = new FileInputStream(f);

In the above example the 'path' directory is below your project's 'war' directory.

查看更多
【Aperson】
6楼-- · 2019-02-08 13:37

If this is part of your application and on the classpath, you should be able to load it using this.getClass().getResource().

查看更多
登录 后发表回答