字节流转换成字符流:
@Test public void test02() throws Exception { Reader r = new BufferedReader(new InputStreamReader( new BufferedInputStream(new FileInputStream(new File("d:/a.txt"))))); Writer w = new BufferedWriter(new OutputStreamWriter( new BufferedOutputStream(new FileOutputStream(new File("d:/a.txt"))))); //空格处, 以字节流转换到字符流, 底层使用适配器模式, 改变客户期望的接口 w.write(2); w.flush(); System.out.print("-----------------------------------------------" + r.read()); }
byte数组和文件的相互转换:
一:
/** * 获得指定文件的byte数组 */ private byte[] getBytes(String filePath){ byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; }
二:
/** * 根据byte数组,生成文件 */ public static void getFile(byte[] bfile, String filePath,String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在 dir.mkdirs(); } file = new File(filePath+"\\"+fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bfile); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }
InputStream转换成字节数组:
package cn.outofmemory.io; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class InputStream2ByteArray { public static void main(String[] args) throws IOException { InputStream in=new FileInputStream("/tmp/req.data"); byte[] data=toByteArray(in); in.close(); FileOutputStream out=new FileOutputStream("/tmp/req2.data"); out.write(data); out.close(); } public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream out=new ByteArrayOutputStream(); byte[] buffer=new byte[1024*4]; int n=0; while ( (n=in.read(buffer)) !=-1) { out.write(buffer,0,n); } return out.toByteArray(); }
}
BufferedImage转换成InputStream:
URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif"); BufferedImage image = ImageIO.read(url); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "gif", os); InputStream is = new ByteArrayInputStream(os.toByteArray());