Java 从Google App Engine应用程序内部读取目录中的所有文件
我知道Google App Engine(GAE)允许您使用以下几种方法读取爆炸战争中的任何文件:Java 从Google App Engine应用程序内部读取目录中的所有文件,java,google-app-engine,file-io,Java,Google App Engine,File Io,我知道Google App Engine(GAE)允许您使用以下几种方法读取爆炸战争中的任何文件: String file = "/WEB-INF/name-of-my-filexml"; InputStream in = getClass().getResourceAsStream(file); 问题是,我需要使用如下目录结构部署我的web应用: MyApp/ WEB-INF/ lib/ classes/ web.xml
String file = "/WEB-INF/name-of-my-filexml";
InputStream in = getClass().getResourceAsStream(file);
问题是,我需要使用如下目录结构部署我的web应用:
MyApp/
WEB-INF/
lib/
classes/
web.xml
appengine-web.xml
...
profiles/
fizz.txt
buzz.txt
foo.txt
... dozens of other text files
我需要一种将每个profiles/*.txt
文件读入Java字符串的方法。在任何人评论之前,为什么不直接硬编码字符串,伙计…,让我们先说,为了发布一个简单的问题,我在这里删掉了很多背景故事。幽默我,让我们假装我不能硬编码字符串。通常,如果我拥有对java.io.*
的完全访问权限,我只会执行以下操作:
File profilesHome = new File("path/to/profiles");
File[] profiles = profilesHome.listFiles();
List<String> profileList = new ArrayList<String>();
for(File profile : profiles)
profileList.add(readFileIntoString(profile));
现在,我如何实现
convertEntryContentsToString(ZipEntry)
?如果您可以将每个.txt文件放入一个Zip文件中,您可以使用ZipInputStream和ZipEntry列出Zip文件中的所有文件(或者如果需要,可以直接访问它们)。查看以下选项是否适用于您:
filelist.txt
的文件,该文件也存在于WEB-INF/profiles
文件夹或从WEB-INF
开始的任何其他文件夹中。此文件可以包含/profiles
文件夹中的文件名列表。每行一个文件名。通过这种方式,您可以逐个解析名称,然后读取文件李>
也许这个代码片段可以帮助您(也许您需要添加一些异常处理、结束代码和其他内容,…): 谢谢@da_re(+1)-请查看原始问题底部的我的更新。是的,我可以将所有内容压缩到
/WEB-INF/profiles.zip
。现在,我正在努力使用“GAE友好”(即不受沙箱限制)的读取器将每个ZipEntry
(一个*.txt文件)转换为java字符串。有什么想法吗?再次非常感谢!
InputStream inputStream = event.getServletContext()
.getResourceAsStream("/WEB-INF/profiles.zip");
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
List<String> list = new ArrayList<String>();
ZipEntry currEntry;
try {
while((currEntry = zipInputStream.getNextEntry()) != null)
// TODO: How to convert the contents of currEntry to a string
// in a manner that is GAE-friendly?
list.add(convertEntryContentsToString(currEntry));
} catch (IOException e) {
e.printStackTrace();
}
while ((zipEntry = zipStream.getNextEntry()) != null) {
String name = zipEntry.getName();
if (!zipEntry.isDirectory()) {
Scanner scanner = new Scanner(zipStream);
StringBuilder builder = new StringBuilder();
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine());
}
String YOURSTRING = builder.toString();
}
}