Java IO工具類

jopen 11年前發布 | 27K 次閱讀 Java Java開發

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**

  • @author
  • @ IO工具類
  • */ public class IOUtil { private IOUtil(){}; /**
  • 將流轉成字符串
  • */ public static String Stream2String(InputStream is)throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream();
     int   i=-1; 
     while((i=is.read())!=-1){ 
     baos.write(i); 
     } 
    return   new String(baos.toByteArray(),"UTF-8"); 
    
    }; /**
  • 將輸入流存儲到byte數組中
  • @param */ public static byte[] in2byte(InputStream is) throws IOException{ byte[] bs= new byte[1024]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len = -1; while((len=is.read(bs))!=-1){ bos.write(bs,0,len); } bs = bos.toByteArray() ; return bs ; }

    /**

  • byte數組轉換成string
  • @param */ public static String toString(byte[] input) throws IOException {

     return new String(input);
    
    

    }

    /**

  • byte數組轉換成string

  • @param charset 編碼格式 */ public static String toString(byte[] input,String charset) throws IOException {
     return new String(input,charset);
    
    } /**
  • 將字符串轉換為輸入流
  • @param charset 編碼格式 */ public static InputStream toInputStream(String input) { byte[] bytes = input.getBytes(); return new ByteArrayInputStream(bytes); } /**

  • 將byte數組轉換為輸入流

  • @param charset 編碼格式 */ public static InputStream byte2InputStream(byte[] b){

    return new ByteArrayInputStream(b); };

    /**

  • 將字符串轉換為輸入流

  • @param input 需要轉換的字符串

  • @param encoding 編碼格式

*/ public static InputStream toInputStream(String input, String encoding) throws IOException {

byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes(); return new ByteArrayInputStream(bytes);

} public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[1024]; while (true) {

int len = in.read(buf); if (len < 0) break;

out.write(buf, 0, len);

}

}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!