# 在 Java 中如何将 InputStream 转换为 String

**URL:** <https://www.isharkfly.com/t/java-inputstream-string/7005>\
**Category:** 程序语言\
**Created:** [May 31, 2013, 12:37pm UTC](https://www.isharkfly.com/t/java-inputstream-string/7005 "2013-05-31T12:37:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [May 31, 2013, 12:37pm UTC](https://www.isharkfly.com/t/java-inputstream-string/7005/1 "2013-05-31T12:37:16Z")

</div>

[code]package com.mkyong.core;

import java.io.BufferedReader;  
import java.io.ByteArrayInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;

public class InputStreamToStringExample {

```
public static void main(String[] args) throws IOException {

	// intilize an InputStream
	InputStream is = 
                 new ByteArrayInputStream("file content..blah blah".getBytes());

	String result = getStringFromInputStream(is);

	System.out.println(result);
	System.out.println("Done");

}

// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {

	BufferedReader br = null;
	StringBuilder sb = new StringBuilder();

	String line;
	try {

		br = new BufferedReader(new InputStreamReader(is));
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (br != null) {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	return sb.toString();

}

```

}[/code]程序输出：`file content..blah blah
Done`
