java处理流多次使用及读取汉字乱码的问题

本文介绍了一种将输入流转换为字符串,再从字符串转换回流的方法,解决了流在处理后无法再次使用的问题。通过将流数据编码为Base64字符串,实现了流的重复利用,适用于需要多次读取同一流数据的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        我们大家都知道,流一经处理后是不能多次使用的,看似简单的小问题,有时会引起一定困扰,为了能再多次使用的时候可以用到,可以将流转化成字符串。然后每次用的时候,再将字符串转化成流,这就达到流重复使用的效果了。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
String fileName ="文件/数据.xls";

// 
InputStream xmlIn1 = null;
InputStream excelIn1 = null;

String filePath = Test.class.getClassLoader().getResource(fileName).getPath();

// 解决读取汉字乱码的问题
filePath = URLDecoder.decode(filePath,"UTF-8");

fileIn1 = new FileInputStream(new File(filePath));

// InputStream fileIn1,将流转成字符串
byte[] excelInBytes = InputStreamUtils.inputStreamToByte(fileIn1);
String excelInBase64 = Base64.encodeBase64String(excelInBytes);

// 将字符串转成多个流
// 流1
InputStream excelIn = InputStreamUtils.byteToInputStream(Base64.decodeBase64(excelInBase64));

// 流2
InputStream excelInOrg = InputStreamUtils.byteToInputStream(Base64.decodeBase64(excelInBase64));
 // 文件路径配置
 String curProjectRoot = System.getProperty("user.dir").replace("\\","/");
 File hd = new File(curProjectRoot);
 if(hd.getParentFile().exists())  hd = hd.getParentFile();
 if(!hd.exists()) hd = new File("E:/");
 if(!hd.exists()) hd = new File("/opt/");
 System.out.println("文件路径: " + hd.getAbsolutePath());
 File logRoot = new File(hd.getAbsolutePath()+"/log/");
 if (!logRoot.exists())
      if(!logRoot.mkdirs())
           System.out.println("logRoot 目录创建失败");
 MathProgramParam.logFileRoot = logRoot.getAbsolutePath();

// 具体方法类

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class InputStreamUtils {

    /**
     * 输入流转字节流
     */
    public static byte[] inputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int ch;
        while ((ch = is.read(buffer)) != -1) {
            byteStream.write(buffer, 0, ch);
        }
        byte data[] = byteStream.toByteArray();
        byteStream.close();
        return data;
    }

    /**
     * 将一个字符串转化为输入流
     */
    public static ByteArrayInputStream byteToInputStream(byte sInputString[]) throws IOException {
        ByteArrayInputStream byteArrayInputStream = null;
        try {
            byteArrayInputStream = new ByteArrayInputStream(sInputString);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return byteArrayInputStream;
    }

    //将byte数组写入文件
    public static void byteArrayToFile(String path, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

    /**
     * 输入流转字节流
     */
    public static String inputStreamToString(InputStream is) throws IOException {
        StringBuilder output = new StringBuilder();
        byte[] buffer = new byte[1024];
        while (is.read(buffer) != -1) {
            String tempStr = new String(buffer, "utf-8");
            output.append(tempStr);
        }
        return output.toString();
    }

    /**
     * 输入流转字节流
     */
    public static String inputStreamToString2(InputStream is) throws IOException {
        StringBuilder output = new StringBuilder();
        byte[] buffer = new byte[1024];
        while (is.read(buffer) != -1) {
            String tempStr = new String(buffer, "utf-8");
            output.append(tempStr.substring(0, tempStr.length()));
        }
        return output.toString();
    }

    static public String streamToString(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n, "UTF-8"));
        }
        return out.toString();
    }

    /**
     * 将一个字符串转化为输入流
     */
    public static ByteArrayInputStream stringToInputStream(String sInputString) {
        ByteArrayInputStream byteArrayInputStream = null;
        try {
            byteArrayInputStream = new ByteArrayInputStream(sInputString.getBytes("utf-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return byteArrayInputStream;
    }


    public static void charOutStream(String fileAllPath, String inputStr) throws IOException {
        // 1:利用File类找到要操作的对象
        File file = new File(fileAllPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        //2:准备输出流
        // Writer out = new FileWriter(file);
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(inputStr.getBytes("utf-8"));
        outputStream.close();
    }

    /**
     * 根据byte数组,生成文件
     *
     * @param bfile    文件数组
     * @param dirPath  文件存放路径
     * @param fileName 文件名称
     */
    public static void byte2File(byte[] bfile, String dirPath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(dirPath);
            if (!dir.exists() && !dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(dirPath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存到文件。
     *
     * @param data 数据
     * @param path 目标文件全路径
     * @param wm   写入模式
     * @return 写入成功与否
     */
    public static boolean byte2File(byte[] data, String path, IOUtils.WriteMode wm) {
        if (data == null || data.length <=0) {
            return false;
        }
        path = path.replace("\\", "/");
        File file = new File(path);
        if (file.exists()) {
            if (IOUtils.WriteMode.EMPTY.equals(wm)) return false; // 文件非空
        } else {
            String[] catalogs = path.split("/");
            String fileName = catalogs[catalogs.length - 1];
            String parentPath = path.substring(0, path.length() - fileName.length());
            File parentFile = new File(parentPath);
            if (!parentFile.exists()) {
                if (!parentFile.mkdirs()) {
                    return false;
                } else {
                    try {
                        if (!file.createNewFile()) {
                            return false;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }
        OutputStream ous = null;
        try {
            if(IOUtils.WriteMode.EMPTY.equals(wm) || IOUtils.WriteMode.COVER.equals(wm)){
                ous = new FileOutputStream(file);
            }else if(IOUtils.WriteMode.END_ADD.equals(wm) ){
                ous = new FileOutputStream(file, true);
            }else{
                ous = new FileOutputStream(file,true);
            }
            ous.write(data);
            ous.flush();
            ous.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (ous != null)
                    ous.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值