在App Engine中如何读取文件?

14

我在App Engine上有一个文件位于/WEB-INF/config.txt,请问在App Engine上该文件的路径是什么?

例如: new File(/*我应该放什么路径在这里?*/)


据我所知,AppEngine 不允许文件上传。您需要将它们声明为静态文件,并通过 URL 访问它们。例如:http://blabla.appspot.com/YOURFILE.txt。 - Thomas Jungblut
5
文件可以被读取,但不能被写入。 - Kyle
6个回答

12
这适用于我:


6

在我这个案例中,我没有访问 ServletContext - getServletContext() 的权限:

下面这种方法对我有用:

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

1
这对我也起作用了。需要强调的一点是,如果您按照这种方式进行操作,在“WEB-INF/config.txt”中的“WEB-INF”之前不要加“/”。 - CKP78

5

在appengine的文档中有关于如何向项目中添加资源的说明,请查看<resource-files>部分,具体内容请参考:如何向项目中添加资源。更多信息可以在appengine沙盒的描述中了解到

当资源被添加到项目中后,您可以使用以下代码来读取它们的内容:

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

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

3
我发现这是获取整个文件字符串的好方法:
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"));

0
  1. 将您的文件放置在 src/main/resources 目录下:

enter image description here

  1. 通过在 appengine-web.xml 中添加以下内容,授予对该文件夹的访问权限:
<resource-files>
    <include path="/resources" />
</resource-files>
  1. 像平常一样在你的代码中使用。例如:
URL resource = EmailSender.class.getClassLoader().getResource("email-template.html");
if (resource != null) {
    File tempFile = new File(resource.getFile());
    if (tempFile.exists()) {
        htmlMessage = FileUtils.readFileToString(tempFile, StandardCharsets.UTF_8);
    }
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接