String/InputStream/File之间的相互转换

String/InputStream/File之间的相互转换InputStrem与String之间转换String转InputStream/***将str转换为inputStream*@paramstr*@return*/publicstaticInputStreamstr2InputStream(Stringstr){ ByteArrayInputStreamis=newByteArrayInputStr…

InputStream与String之间转换

String转InputStream

/**
 * 将str转换为inputStream
 * @param str
 * @return
 */
public static InputStream str2InputStream(String str) {
	ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
	return is;
}

InputStream转String

/**
 * 将inputStream转换为str
 * @param is
 * @return
 * @throws IOException
 */
public static String inputStream2Str(InputStream is) throws IOException {
	StringBuffer sb;
	BufferedReader br = null;
	try {
		br = new BufferedReader(new InputStreamReader(is));

		sb = new StringBuffer();

		String data;
		while ((data = br.readLine()) != null) {
			sb.append(data);
		}
	} finally {
		br.close();
	}

	return sb.toString();
}

InputStream与File之间转换

File转InputStream

/**
 * 将file转换为inputStream
 * @param file
 * @return
 * @throws FileNotFoundException
 */
public static InputStream file2InputStream(File file) throws FileNotFoundException {
	return new FileInputStream(file);
}

InputStream转File

/**
 * 将inputStream转化为file
 * @param is
 * @param file 要输出的文件目录
 */
public static void inputStream2File(InputStream is, File file) throws IOException {
	OutputStream os = null;
	try {
		os = new FileOutputStream(file);
		int len = 0;
		byte[] buffer = new byte[8192];

		while ((len = is.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
	} finally {
		os.close();
		is.close();
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35346.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注