java - Java 从 Apache IOUtils 转换的字符串中取回 InputStream
问题描述
我正在使用库Sharepoint-Java-API从 Sharepoint 下载文件。
我能够下载文件,但得到了字符串格式,使用org.apache.commons.io.IOUtils
as进行转换
public static String get(Pair<String, String> token, String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("Cookie", token.getLeft() + ";" + token.getRight());
getRequest.addHeader("accept", "application/json;odata=verbose");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() == 200) {
return IOUtils.toString(response.getEntity().getContent(), "utf-8");
} else {
System.err.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + ", " + url);
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException ex) {
Logger.getLogger(SPOnlineMFT.class).error(ex);
}
}
return null;
}
现在我正在尝试将其转换为InputStream并将其保存在本地文件系统中以进行测试
呼叫者:-
String content = SPOnline.get(token, domain, url );
if (content != null) {
File targetFile = new File("D:\\Rivian\\SharePoint\\TempDownload/"+fileName);
// InputStream stream = new ByteArrayInputStream(content.getBytes("utf-8"));
InputStream stream = IOUtils.toInputStream(content, "utf-8");
Files.copy(stream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File Downloaded")
}
但我无法读取/打开文件,例如 MS excel 文件。打开文件时收到消息为损坏的文件。
解决方案
只需将字节数组直接写入文件,无需将其转换为 utf-8 字符串。
import java.nio.file.Files;
import java.nio.file.Path;
Path file = Path.of("D:\\SharePoint\\TempDownload/"+fileName);
Files.write(file, response.getEntity().getContent()));
推荐阅读
- java - 从 Spring @PostMapping 方法返回多个文件
- .net - Powershell SaveFileDialog - 弹出两次
- javascript - 在ajax函数之后全局使用变量
- javascript - 由于输入类型搜索出现红色框,无法继续浏览网页,这仅在 IE 中出现,在 chrome 中不出现
- kentico-12 - Kentico 12 Service Pack - MVC 站点仅重定向到管理站点登录页面
- .net - 在 .NET Core 中干燥 Azure 函数应用程序
- python - 正则表达式匹配失败
- ios - 应用程序未在 TestFlight 中显示为 App Store Connect 用户
- c++ - 如何仅使用邻接表在无向图中找到存在的循环(顶点也没有)?
- java - 在 Windows 中运行时,Java 中的 python 脚本子进程不会被破坏