String str = "";//add your string content
InputStream inputStream = new ByteArrayInputStream(str.getBytes());
1 package org.kodejava.example.io;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.InputStream;
5
6 public class StringToStream {
7 public static void main(String[] args) {
8 String text = "Converting String to InputStream Example";
9
10 /*
11 * Convert String to InputString using ByteArrayInputStream class.
12 * This class constructor takes the string byte array which can be
13 * done by calling the getBytes() method.
14 */
15 try {
16 InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
17 } catch (UnsupportedEncodingException e) {
18 e.printStackTrace();
19 }
20 }
21 }
22
1、字符串轉inputStream
- String string;
-
- InputStream is = new ByteArrayInputStream(string.getBytes());
2、InputStream轉字符串
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int i;
- while ((i = is.read()) != -1) {
- baos.write(i);
- }
- String str = baos.toString();
- System.out.println(str);
3、String寫入OutputStream
- OutputStream os = System.out;
- os.write(string.getBytes());
4、OutputStream寫入String
這聽起來有點荒謬,OutputStream本來就是輸出源,還寫入String?
不過最近項目里確實遇到了個類似的問題,比如 SOAPMessage.writeTo(OutputStream os) 這個方法,是將SOAPMessage的內容寫到一個輸出流中,而我想得到這個流的內容,總不能把他先寫進文件再去讀這個文件吧,研究了好半天,終于想起可以如下這般:
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- String str = baos.toString();
這里需要用到一個特殊的類ByteArrayOutputStream,利用他,我們可以將輸出流在內存中直接轉換成String類型。
具體代碼如下:
首先從輸入流中將數據讀出來寫入ByteArrayOutputStream,然后再將其轉換成String.
- InputStream in = urlconn.getInputStream();
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
-
- byte[] buffer = new byte[2048];
- int length = 0;
- while((length = in.read(buffer)) != -1) {
- bos.write(buffer, 0, length);
- }
- in.close();
-
-
- new String(bos.toByteArray(), "UTF-8");
-
-
根據同樣的原理,我們可以將outputstream直接轉換成String對象。
指定一下字符集
byte[] b = str.getBytes("utf-8");
String s = new String(b,"utf-8");
OUTPUTSTREAM中方法WRITE用法
void write(byte[] b)
將 b.length 個字節從指定的 byte 數組寫入此輸出流。
void write(byte[] b, int off, int len)
將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此輸出流。
abstract void write(int b)
將指定的字節寫入此輸出流。
轉載地址:
http://blog.csdn.net/soundtravel/article/details/6927006
posted on 2013-07-11 16:18
ForMeBlog 閱讀(353)
評論(0) 編輯 收藏 所屬分類:
JAVA基礎類