使用ByteArrayOutputStream写入字符串

package com.gk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
 * 使用ByteArrayOutputStream写入字符串
 * @author GuoKe
 *说明:1,不关联源	2.可以不释放资源	3.使用toByteArray()获取数据
 */
public class IOTest8 {
     

	public static void main(String[] args) {
     
		
		byte[] dest = null;
		
		ByteArrayOutputStream bs = null;
		
		try {
     
			bs = new ByteArrayOutputStream();
			
			String str = "hello";
			byte[] datas = str.getBytes();
			bs.write(datas,0,datas.length);
			bs.flush();
			dest = bs.toByteArray();
			System.out.println(dest.length + ":" + new String(dest,0,dest.length/*bs.size()*/));
		}catch(FileNotFoundException e){
     
			e.printStackTrace();
		}catch(IOException e){
     
			e.printStackTrace();
		}finally {
     
			try {
     
				if (bs != null) {
     //alt+shift+z
					bs.close();
				} 
			} catch (Exception e) {
     
				e.printStackTrace();
			}
		}

	}

}

你可能感兴趣的:(java学习,IO流)