黑马程序员----输入输出流IO(一)

长平狐 发布于 2013/07/01 15:31
阅读 201
收藏 1

-------------------------android培训java培训、期待与您交流! -------------------------

IO是输入input和输出output的简写

流按照操作数据分为两种:字节流与字符流

流按流向分为:输入流,输出流。

IO流常用基类:

  字节流的抽象基类:

InputStream, OutputStream.

  字符流的抽象基类:

Reader,  Writer

  这四个类派生出来的子类名称都是以其父类名称作为子类的后缀名

如:InputStream的子类FileInpputStream

    Reader的子类FileReader.

用FileWriter类实现文件的写入操作

private static void writeFile(){
		FileWriter fw =null;
		try {
			//fw = new FileWriter("c:\\abc.txt");这种方式如果文件存在,直接覆盖
			fw = new FileWriter("c:\\abc.txt",true);//如果文件存在,可接在已有内容后面写
			fw.write("abc");
			fw.write("dddd");
			fw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
                     //关闭流时先要判断流是否为空
				if(fw!=null)
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

利用字符数组通过FileRead类实现读取文件内容的操作

private static void readFileUseArray(){
		FileReader fr = null;
		try {
			fr = new FileReader("c:\\abc.txt");
			char [] buf = new char[512];
			int num = 0;
			while((num = fr.read(buf))!=-1){
				System.out.println("num:"+ num + "....."+ new String(buf,0,num));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fr !=null){
				try {
					fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

两种方式复制文件

//第一种方式,读一个字符就写一个字符
	private static void copyFile1() throws IOException{
		FileReader fr = new FileReader("E:\\workspace\\test\\src\\io\\FileWriterTest.java");
		FileWriter fw = new FileWriter("c:\\copy_test1.txt");
		int ch = 0;
		while((ch = fr.read())!=-1){
			fw.write(ch);
		}
		fr.close();
		fw.close();	
	}
	
	//第二种方式,定义一个数组,每次读一定长度的数据存储到目标文件中
	private static void copyFile2()throws IOException{
		FileReader fr = new FileReader("E:\\workspace\\test\\src\\io\\FileWriterTest.java");
		FileWriter fw = new FileWriter("c:\\copy_test2.txt");
		char[] c = new char[1024];
		int len=0;
		while((len=fr.read(c))!=-1){
			fw.write(new String(c,0,len));
		}
		fr.close();
		fw.close();	
	}
}

缓冲

为了提高字符读写流效率,加入了缓冲技术

只要将需要被提高效率的流对象作为参数传递给缓冲区构造函数即可。

只要用到写缓冲,最后都要调用flush();

其实,关闭缓冲区就是在关闭缓冲区中的流对象,所以不用另外再关流对象。

BufferedWriter提供了一个跨平台的换行方法newLine()。

private static void bufferWriterTest(){
		try {
			FileWriter fr = new FileWriter("c:\\bufferWriter.txt");
			BufferedWriter bw = new BufferedWriter(fr);
			bw.write("abcdefghijklmnopqrstuvwxyz");
			bw.newLine();
			bw.write("abcdefghijklmnopqrstuvwxyz");
			//使用了缓冲就一定要flush
			bw.flush();
			//关闭了缓冲就相当于关掉了流对象fr,所以不需要另外关闭
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

BufferedReader提供了一个readLine()方法,方便了字符读取,提高读取数据效率。

private static void bufferReaderTest(){
		try {
			//创建一个读取对象和文件相关联
			FileReader fr = new FileReader("E:\\workspace\\test\\src\\io\\BufferTest.java");
			//创建一个缓冲,提高读取效率
			BufferedReader br = new BufferedReader(fr);
			 String line=null;
			 //字符读取缓冲区,提供了一个readLine()方法,方便字符的读取
			 while((line = br.readLine())!=null){
				 System.out.println(line);
			 }
			 br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

使用缓冲技术复制一个java文件

//使用缓冲技术copy一个java文件
    private static voidcopyjavaFileByBuffer(){
        BufferedReaderbr =null;
        BufferedWriterbw =null;
        try {
            br = new BufferedReader(new FileReader("E:\\workspace\\test\\src\\io\\BufferTest.java"));
            bw = new BufferedWriter(new FileWriter("c:\\buffer_copy.txt"));
            Stringline = null;
            while((line =br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
        } catch (FileNotFoundException e){
            System.out.println("文件找不到" );
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           
        }
    }

其实BufferedWriter中的newLine()方法内部也是采取的FileReader的write方法实现的。

装饰设计模式

当想要对已有的对象进行功能增强时,可以定义类,将已有的对象传入,急于已有的功能,并提供加强功能,那么自定义的该类称为装饰类。

装饰类通常会通过构造方法接收被装饰的对象,并基于被装饰的对象功能,提供更强的功能。

//先定义一个Person类,类里面有一个eat()方法

再定义一个类EnhancePerson,其构造方法中将Person的对象p以参数的形式传入。

重新写一个方法enhanceEat(),方法中除了包含Person类中的方法eat()方法外,还增加了其他方法,是为增强其功能


字节流

InputStream OutputStream

需求,如果操作图片或者字节数据,这时就要用到字节流。

以下代码演示了利用FileInputStream和FileOutputStream进行文件的读写

//字节流向文件中写入数据
private static void writeStream(){
		try {
			FileOutputStream fos = new FileOutputStream("c:\\writerStream.txt");
			fos.write("abcdefgh".getBytes());
			//字节流写操作时不需要flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	//字节流从文件中读取数据
	private static void readStream(){
		try {
			FileInputStream fis = new FileInputStream("c:\\writerStream.txt");
			int ch = 0;
			while((ch=fis.read())!=-1){
				System.out.println((char)ch);
			}
                fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
     //更高效的从文件中读操作
	private static void readStream2(){
		try {
			FileInputStream fis = new FileInputStream("c:\\writerStream.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();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

以下代码演示了利用字节流copy图片

private static void copyImage(){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("c:\\mm1.jpg");
			fos = new FileOutputStream("c:\\mm2.jpg");
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=fis.read(buff))!=-1){
				fos.write(buff, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fis !=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

















------------------------- android培训java培训、期待与您交流! -------------------------

原文链接: http://blog.csdn.net/voiceofnet/article/details/7281546
加载中
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部