如何在App Engine中读取文件?

时间:2011-05-17 17:01:32

标签: java google-app-engine

我在应用引擎上的/WEB-INF/config.txt处有一个文件。应用引擎上文件的路径是什么?

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

5 个答案:

答案 0 :(得分:12)

这对我有用:

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

答案 1 :(得分:5)

appengine how to add resources to your project上有一些文档。查看< resource-files>部分。可以在the description of the appengine sandbox中阅读更多信息。

将资源添加到项目后,您可以使用以下代码来阅读其内容:

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

在上面的示例中,'path'目录位于项目的'war'目录下。

答案 2 :(得分:5)

就我而言,我无法访问 ServletContext - getServletContext():

这对我有用:

InputStream inputStream = new FileInputStream(new File("WEB-INF/config.txt"));

答案 3 :(得分:3)

我发现这是一个在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"));

答案 4 :(得分:0)

如果这是您的应用程序和类路径的一部分,您应该能够使用this.getClass()。getResource()加载它。

相关问题