JAVA数据流之间的转换

http://blog.csdn.net/liuhenghui5201/article/details/8292552

InputStream.read(byte[] b)

从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。

OutputStream.write(byte[] b) 

b.length 个字节从指定的 byte 数组写入此输出流。

PrintWriter(Writer out) 
创建不带自动行刷新的新 PrintWriter。

 

String urlPath="";URL url=new URL(urlPath);

HttpURLConnectioncoon=

(HttpURLConnection)url.openConnection();

字符流->字节流:

String s=asasaa;

printWriter pw=new printWrite(conn.getoutputStream);

Pw.print(s);           pw.flush();

 byte[] s= str.getBytes();

字节流->字符流:

bufferedReader br=new bufferedRead(new inputStreamReader(conn.getinputStream);

String result=””;

While(String line=br.readLine()!=null){result+=line;}

InputStreamReader(new inputstream())

通常 Writer 将其输出立即发送到底层字符或字节流。除非要求提示输出,否则建议用 BufferedWriter 包装所有其 write() 操作可能开销很高的 Writer(如 FileWriters 和 OutputStreamWriters)。例如,

 PrintWriter out

   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

同理BufferedReader in

   = new BufferedReader(new FileReader("foo.in"));

 

1.字节流和字符流之间的转换

字节流转换成字符流可以用InputSteamReader/OutputStreamWriter相互转换.

输出字符流

  1.  OutputStream out = System.out;//打印到控制台。  
  2.  OutputStream out = new FileOutputStream("D:\\demo.txt");//打印到文件。  
  3.             OutputStreamWriter osr = new OutputStreamWriter(out);//输出  
  4. BufferedWriter bufw = new BufferedWriter(osr);//缓冲 
  1. String str = "你好吗?\r\n我很好!";//你好吗?  
  2.             bufw.write(str);  
  3.             bufw.flush();  
  4.             bufw.close(); 

读取字节流

  1. InputStream in = System.in;//读取键盘的输入。  
  2. InputStream in = new FileInputStream("D:\\demo.txt");//读取文件的数据。  

//将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.  

  1.         InputStreamReader isr = new InputStreamReader(in);//读取  
  1.  char []cha = new char[1024];  
  2.         int len = isr.read(cha);  
  3.         System.out.println(new String(cha,0,len));  
  4.         isr.close(); 

 

2.怎么把字符串转为流. 下面的程序可以理解把字符串line 转为流输出到aaa.txt中去

FileOutputStream fos = null;
fos = new FileOutputStream("C:\\aaa.txt");

String line="This is 1 line";
fos.write(line.getBytes());
fos.close();

字符串与字节流转换

  1. static String src = "今天的天气真的不好";  
  2.     public static void main(String[] args) throws IOException {  
  3.           StringBuilder sb = new StringBuilder();
  4.         byte[] buff = new byte[1024];  
  5.         //从字符串获取字节写入流  
  6.         InputStream is = new ByteArrayInputStream(src.getBytes("utf-8"));  
  7.         int len = -1;  
  8.         while(-1 != (len = is.read(buff))) {  
  9.             //将字节数组转换为字符串  
  10.             String res = new String(buff, 0, len);  
  11.             Sb.append(res);}

猜你喜欢

转载自blog.csdn.net/xxdw1992/article/details/81168917