Java 从 Apache IOUtils 转换的字符串中取回 InputStream [英] Java Get back InputStream from String Converted by Apache IOUtils

查看:48
本文介绍了Java 从 Apache IOUtils 转换的字符串中取回 InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用库 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆