如何解决Java 从 Apache IOUtils 转换的字符串中取回 InputStream
我正在使用库 Sharepoint-Java-API 从 Sharepoint 下载文件。
我能够下载文件,但获得了 String 格式,该格式使用 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()));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。