InputStream、String互相转换

1.InputStream转String

/*
     *	InputStream转字符串
     */
    public String inputstrToStr(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[0];
        bytes = new byte[inputStream.available()];
        // 读取文件内容到字节数组
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = inputStream.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        // 读取完毕的校验
        if (offset < bytes.length) {
            throw new IOException("不能完全讀取文件");
        }
        inputStream.close();
        String encodedFileString = Base64.getEncoder().encodeToString(bytes);
        return encodedFileString;
    }

2.String转InputStream

	/*
	 *	字符串转InputStream
	 */
	public  InputStream str2Inputstr(String inStr) {
		try {
			byte[] bytes = Base64.getDecoder().decode(inStr);
			return new ByteArrayInputStream(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

猜你喜欢

转载自blog.csdn.net/after_17/article/details/119879990
今日推荐