黑马程序员java基础之IO流中的字节流

来源:互联网 发布:statistic软件教学 编辑:程序博客网 时间:2024/05/22 10:50
------- android培训、java培训、期待与您交流! ----------

操作图片数据,就要用到字节流:InputStream(读),OutputStream(写)

1.用字节读写流读写一个文件

import java.io.*;class FileStream{public static void main(String[] args) throws IOException{writeFile();readFile_2();}public static void readFile() throws IOException{FileInputStream fis=new FileInputStream("fos.txt");int ch=0;while((ch=fis.read())!=-1){System.out.println((char)ch);//一个字节一个字节的读}fis.close();}public static void readFile_1() throws IOException{FileInputStream fis=new FileInputStream("fos.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();}public static void readFile_2() throws IOException{FileInputStream fis=new FileInputStream("fos.txt");int num=fis.available();byte[] buf=new byte[num];//创建一个刚刚好的数组缓冲区System.out.println(num);fis.read(buf);//数组缓冲区刚好合适,就不用循环了System.out.println(new String(buf));fis.close();}public static void writeFile() throws IOException{FileOutputStream fos=new FileOutputStream("fos.txt");fos.write("abcde".getBytes());fos.close();}}

练习:复制一张图片

   步骤:用字节读取流对象和图片关联

    用字节写入流创建一个图片文件,用于存储获取到的图片数据

    通过循环读写,完成数据的存储

   关闭资源

import java.io.*;class CopyPicture{public static void main(String[] args){FileOutputStream fos=null;FileInputStream fis=null;try{fos=new FileOutputStream("e:\\p2.jpg");fis=new FileInputStream("c:\\p1.jpg");byte[] buf=new byte[1024];int len=0;while((len=fis.read(buf))!=-1){fos.write(buf,0,len);}}catch(IOException e){throw  new RuntimeException("复制文件失败");}finally{try{if(fis!=null)fis.close();}catch(IOException e){System.out.println(e.toString());}try{if(fos!=null)fos.close();}catch(IOException e){System.out.println(e.toString());}}}}

对于字节流的缓冲区,通过复制Mp3来演示

import java.io.*;class CopyMusic{public static void main(String[] args)throws IOException{long start=System.currentTimeMillis();//拷贝开始时间copy_1();long end=System.currentTimeMillis();//拷贝结束时间System.out.println(end-start);}public static void copy_1() throws IOException{FileInputStream fis=new FileInputStream("e:\\feng.mp3");FileOutputStream fos=new FileOutputStream("c:\\feng1.mp3");//建立字节缓冲区,并把流对象存入BufferedInputStream bufi=new BufferedInputStream(fis);BufferedOutputStream bufo=new BufferedOutputStream(fos);int by=0;while((by=bufi.read())!=-1)//当没有读取到字节流的末尾时{bufo.write(by);//写入字节缓冲区中}//关闭流资源bufi.close();bufo.close();}}

自定义一个字节缓冲区
import java.io.*;class MyBufferedInputStream{private InputStream in;private byte[] buf=new byte[1024*4];private int pos=0,count=0;MyBufferedInputStream(InputStream in){ this.in=in;}//一次读一个字符,从缓冲区获取public int MyRead() throws IOException{if(count==0){count=in.read(buf);//通过in对象读取硬盘上的数据,并存入buf中,用count计数读的个数if(count<0)return -1;pos=0;byte b=buf[pos];//取0角标元素,即第一个元素count--;pos++;return b&255;/*读到的头8个字节是111-11111,即为-1,如此在循环中就符合条件,会让虚拟机误以为是已经到了数据流的末尾,而返回值是int型就可以将字节提升,变成111-11111 111-11111 111-11111 111-11111,这样将-1前面的值补0即0000-0000 0000-0000 0000-0000 111-11111这样既可以提升字节,还可以避免与判断位的-1相同,可以继续循环而不会出现复制的音乐文件是0kb了,所以返回时,b&255就会将byte提升为int时,前面补0*/}else if(count>0)//取出剩下的元素{byte b=buf[pos];count--;pos++;return b&0xff;}return -1;}public void myclose() throws IOException{in.close();}}

读取键盘录入数据

import java.io.*;class ReadIn{public static void main(String[] args) throws IOException{InputStream in =System.in;//获取键盘录入对象StringBuilder sb=new StringBuilder(in);建立字符缓冲区while(true){int ch=in.read();if(ch=='\r')continue;if(ch=='\n'){String s=sb.toString();if("over".equals(s))//如果输入的是“over”,则停止break;System.out.println(s.toUpperCase());sb.delete(0,sb.length()); //发现键盘不断输入的时候,字符串越来越长,//所以需要执行该动作在完成一次打印后就清空缓冲区}elsesb.append((char)ch);}in.close();}}

转换流:InputStreamReader 将字节流对象转换成字符流,OutputStreamWriter将字符流对象转换成字节流

  注意:当涉及到字符编码转换时需要用到转换流,操作的文件字节输出流:FileOutputStream

import java.io.*;class TransStreamDemo{public static void main(String[] args)throws IOException{InputStream in=System.in;//获取键盘录入对象InputStreamReader isr=new InputStreamReader(in);//用转换流InputStreamReader将字节流对象转换成字符流对象,BufferedReader bufr=new BufferedReader(isr);//为了提高效率,对字符串使用缓冲区技术,OutputStream out=System.out;//获取控制台输出对象OutputStreamWriter osw=new OutputStreamWriter(out);//使用转换流将字符流转换成字节流BufferedWriter bufw=new BufferedWriter(osw);//使用缓冲区技术,提高效率//开始循环,输出字符流数据String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;bufw.write(line.toUpperCase());bufw.newLine();//转行bufw.flush();//刷新}bufr.close();}}


流操作的基本规律:通过三个明确来完成

明确源和目的

源:输入流,InputStream  Reader

目的:输出流,OutputStream   Writer

操作的数据是否为纯文本

是:字符流;否:字节流

当体系明确后,再明确要使用哪个具体的对象

通过设备来进行区分:源设备:内存,硬盘,键盘

目的设备:内存,硬盘,控制台

改变标准输入输出设备System.setIn(new FileInputStream("demo.java")); System.setout(new PrintStream("z.txt"))


异常处理日志的建立

import java.io.*;import java.util.*;import java.text.*;class ExceptionInfo{public static void main(String[] args){try{int[] arr= new int[2];System.out.println(arr[3]);}catch(Exception e){try{Date d=new Date();//创建时间对象SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//创建格式化时间的对象String s=sdf.format(d);将时间传入到格式对象中PrintStream ps=new PrintStream("exeception.log");ps.println(s);System.setOut(ps);  //重置目的对象,便于记录异常事件}catch(IOException e1){throw new RuntimeException("日志文件创建失败");}e.printStackTrace(new PrintStream(System.out));//将异常记录到文件中}}}


系统信息的处理

import java.util.*;import java.io.*;class SystemInfo{public static void main(String[] args) throws IOException{Properties prop=System.getProperties();//获取系统的属性信息//System.out.println(prop);prop.list(new PrintStream("sys.txt"));//在打印流中创建文本文档保存系统信息}}









0 0
原创粉丝点击