Java IO工具類
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>