Java从Apache IOUtils转换后的字符串中获取InputStream [英] Java Get back InputStream from String Converted by Apache IOUtils
问题描述
我正在使用库 Sharepoint-Java-API 从以下位置下载文件共享点.
我可以下载文件,但使用 String 格式,该格式是通过 org.apache.commons.io.IOUtils
as
I am using library Sharepoint-Java-API to download Files from Sharepoint.
I am able to download file but got as String format which is converted using 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 并将其保存在本地文件系统中进行测试
Now I am trying to convert it to InputStream and save it local file system for testing
呼叫者:-
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文件.打开文件时收到消息为损坏的文件.
but I am not able to read/open file e.g. MS excel file. While opening file got message as corrupted file.
推荐答案
只需将字节数组直接写入文件,而无需将其转换为utf-8字符串.
Just write byte array directly into file, without converting it to utf-8 string.
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从Apache IOUtils转换后的字符串中获取InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!