String/InputStream/File之間的相互轉換

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();
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章