字节流常用来处理图片文件等,不包含编码表。
常用基本类之字节流:InputStream:OutputStream
1.FileInputStream和FileOutputStream
字节流和字符流的使用方法一样,需要注意的是因为操作的是最小数据单位,所以不需要刷新,但是需要关闭流。
写入:
FileOutputStream fos = new FileOutputStream("/Volumes/Function/G/demo.txt");//创建文本文件 fos.write("abc".getBytes());//写入流中 fos.close();//关闭之前会刷新一次内部缓冲,将数据刷到目的地中,flush刷新会继续使用。 读取:1.1
FileInputStream fis = new FileInputStream("/Volumes/Function/G/demo_test.txt") ; byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf)) != -1){ System.out.println(new String(buf,0,len)); } fis.close(); 1.2 FileInputStream fis = new FileInputStream("/Volumes/Function/G/demo_stream.txt") ; int num = fis.available();//获取到当前文本中所有的字节数,便于定义一个数据量大小合适的数组 byte[] buf = new byte[num]; fis.read(buf); System.out.println(new String(buf)); fis.close(); 复制一张图片: FileOutputStream fos = new FileOutputStream("/Volumes/Function/G/112_copy.jpg"); FileInputStream fis =new FileInputStream("/Volumes/Function/G/112.jpg"); byte[] buf = new byte[1024*1024]; int len = 0; while((len = fis.read(buf)) != -1){ fos.write(buf,0,len); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } 2.BufferedOutputStream和BufferedInputStream字节流缓冲区和字符流缓冲区用法相似,这里不再赘述。