zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

转换 string File 之间 相互 inputstream
2023-06-13 09:14:46 时间

大家好,又见面了,我是你们的朋友全栈君。

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://javaforall.cn/191067.html原文链接:https://javaforall.cn