【发布时间】:2020-12-06 02:48:22
【问题描述】:
我正在尝试使用 Google Drive API 获取 Google 文档的内容。我成功获取了文件夹并获得了 Google Docs 文件 ID。
在API文档上,据说我可以下载这样的文件:
private String getGdoc(String id) throws Exception {
if(service == null) throw new Exception();
OutputStream outputStream = new ByteArrayOutputStream();
service.files().export(id, "text/plain")
.executeMediaAndDownloadTo(outputStream);
return null;
}
我的问题是我不想将其写入带有OutputStream 的文件,但我想将文件的内容写入String。
所以我尝试使用InputStream:
private String getGdoc(String id) throws Exception {
if(service == null) throw new Exception();
InputStream inputStream = service.files().export(id, "text/plain")
.executeMediaAsInputStream();
System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
return null;
}
使用InputStream 我得到了文件的内容,但是我的文档中有一些日文字符并且它们没有显示出来。对于控制台中的这些日文字符,我只得到?。我不知道它来自哪里,因为我指定使用 UTF-8 字符集。
当我尝试使用OutputStream 写入txt 文件时,我没有遇到无法识别字符的问题。
我不知道实现这一目标的最佳方法是什么。你能帮帮我吗?
【问题讨论】:
-
很有可能您的
String包含正确的数据,并且您打印它的控制台无法显示日文字符(因此将其替换为?)。尝试将String序列化为其他格式(如 JSON 文件或 XML,使用适当的库),看看是否足够)。 -
你说得对,这只是控制台的问题。当我在 JTextArea 中显示它时没有问题。
标签: java google-api google-drive-api google-docs-api google-api-java-client