Java IO操作总结

IO 就是Input和Output的缩写

使用较多的是对文件的操作:字节流和字符流

    1.字符流有两个抽象类:Writer   Reader

其对应子类FileWriterFileReader可实现文件的读写操作

BufferedWriterBufferedReader能够提供缓冲区功能,用以提高效率

    2.字节流也有两个抽象类:InputStream   OutputStream

其对应子类有FileInputStreamFileOutputStream实现文件读写

BufferedInputStreamBufferedOutputStream提供缓冲区功能

    3.什么时候该使用字符流,什么时候又该使用字节流呢?

所谓字符流,肯定是用于操作类似文本文件或者带有字符文件的场合比较多

而字节流则是操作那些无法直接获取文本信息的二进制文件,比如图片,mp3,视频文件等

在硬盘上都是以字节存储的,字符流在操作文本上面更方便一点而已

    4.为什么要利用缓冲区呢?

试想一下,如果一有数据,不论大小就开始读写,势必会给硬盘造成很大负担,

人不也一样,一顿饭不让你一次吃完,每分钟喂一勺,你怎么想?

因此,采用缓冲区能够在读写大文件的时候有效提高效率

Exzample 1 取文件

import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 
  
public class Demo { 
    public static void main(String[] args ) { 
          
        //创建要操作的文件路径和名称 
        //其中,File.separator表示系统相关的分隔符,Linux下为:/  Windows下为:\\
	//System.getProperty("user.dir")获取当前工程的根目录
        String path = System.getProperty("user.dir") + 
		      File.separator + "src" + 
		      File.separator + "main" +  
              File.separator + "resources" + 
		      File.separator + "filepath" +
              File.separator + "test.txt"; 
      
        //由于IO操作会抛出异常,因此在try语句块的外部定义FileWriter的引用 
        FileWriter w = null; 
        try { 
            //以path为路径创建一个新的FileWriter对象 
            //如果需要追加数据,而不是覆盖,则使用FileWriter(path,true)构造方法 
            w = new FileWriter(path);          
            //将字符串写入到流中,System.getProperty("line.separator")表示换行 
            w.write("What a beautyful day!");
            w.write(System.getProperty("line.separator")); 
            //如果想马上看到写入效果,则需要调用w.flush()方法 
            w.flush(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally { 
            //如果前面发生异常,那么是无法产生w对象的  
            //因此要做出判断,以免发生空指针异常 
            if(w != null) { 
                try { 
                    //关闭流资源,需要再次捕捉异常 
                    w.close(); 
                } catch (IOException e) { 
                    e.printStackTrace(); 
                } 
            } 
        } 
    } 
 }

     

Exzample 2 字节流的缓冲区文件复制

//其他部分代码参考Exzample 1
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bo = new BUfferedOutputStream(new FileOutputStream(copy));

byte[] buf = new byte[1024];
int temp = 0;
while((temp = bi.read(buf)) != -1){
    bo.write(buf,0,temp);
}

猜你喜欢

转载自iven-huang.iteye.com/blog/2219980