通过ByteArrayOutputStream将inputStream转变为outputStream
1.首先,先编写一个获取文件输入流的方法 ops()。
2. 之后在调用此方法获得输入流,并通过 castToBAOStream(Object obj,int bufferSize)进行转化。
3.最后,写出 转化成功的 输出流。
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
- public class Stream {
- public static final int StreamFlushBufferSzie=100;//buffer size= 1K
- public static ByteArrayOutputStream castToBAOStream(Object obj,int bufferSize){
- // Log logger = LogFactory.getLog(CommonUtil.class);
- ByteArrayOutputStream baos=new ByteArrayOutputStream();
- if(obj.getClass().isInstance(baos)){
- return (ByteArrayOutputStream)obj;
- }else{
- InputStream fis;
- try{
- fis=(FileInputStream)obj;
- try{
- BufferedInputStream bis=new BufferedInputStream(fis);
- baos=new ByteArrayOutputStream();
- BufferedOutputStream bos=new BufferedOutputStream(baos);
- int ch;
- int i=0;
- while((ch=bis.read())!=-1){
- bos.write(ch);
- if(i++==bufferSize){
- bos.flush();
- i=0;
- }
- }
- bos.flush(); //提交文件流,很关键
- bis.close();
- return baos;
- }catch(ClassCastException e){
- // logger.info("Stream object not a ByteArrayOutputStream or a FileInputStream:",e);
- return null;
- }catch(Exception e){
- // logger.info("baos is null:",e);
- return null;
- }
- }catch(ClassCastException e){
- fis=(InflaterInputStream)obj;
- try{
- baos=new ByteArrayOutputStream();
- BufferedOutputStream bos=new BufferedOutputStream(baos);
- int ch;
- int i=0;
- // ii.read(b, off, len)
- byte[] by = new byte[2048];
- while((ch=fis.read(by))!=-1){
- bos.write(by,0,ch);
- if(i++==bufferSize){
- bos.flush();
- i=0;
- }
- }
- bos.flush(); //提交文件流,很关键
- fis.close();
- // ZipUtil.getZipName().close();
- return baos;
- }catch(ClassCastException e1){
- // logger.info("Stream object not a ByteArrayOutputStream or a FileInputStream:",e1);
- return null;
- }catch(Exception e1){
- // logger.info("baos is null:",e1);
- return null;
- }
- }
- }
- }
- //产生一个文件输入流
- public static InputStream ops() throws FileNotFoundException {
- File file = new File("d://lin.txt");
- FileInputStream fileInputStream = new FileInputStream(file);
- return fileInputStream;
- }
- public static void main(String[] args) throws IOException {
- try {
- // OutputStream outputStream = ops();
- InputStream inputStream = ops();
- ByteArrayOutputStream baos = castToBAOStream(inputStream,StreamFlushBufferSzie);
- InputStream is = new ByteArrayInputStream(baos.toByteArray());
- File file=new File("d://new.txt");
- FileOutputStream outb=new FileOutputStream(file);
- int bytesRead;
- byte[] buf = new byte[4 * 1024];
- while((bytesRead = is.read(buf))!=-1){
- outb.write(buf,0,bytesRead);
- }
- outb.flush();
- outb.close();
- is.close();
- System.out.println(inputStream);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
转载于:https://blog.51cto.com/gswxr/719013