IO输入输出流——Java面向对象基础(29)

一、概念

IO(输入输出流)

InputStream 输入流

OutputStream 输出流

 

输入输出流广义上就是物理存储介质、设备、容器数据的传输过程。

 

Java中提供一个强大的api操作IO,java.io包

二、常见的File类

  File常常用于操作系统文件或目录,其中常用的方法务必掌握。

  File file = new File("填写文件|文件目录的路径");

  createNewFile()  创建文件

  delete()   删除文件或目录

  exists()  判断文件或目录是否存在

  mkdir() 创建目录

  mkdirs() 创建目录(父目录)

  listRoots() 列出可用的文件系统根。

  File.listRoots()[index].listFiles()  获取某个磁盘的所有文件目录

  getAbsoluteFile() 返回此抽象路径名的绝对形式。

  file.getAbsoluteFile().getAbsolutePath()  获取绝对路径 -- String字符路径

  toURI() 构造一个表示此抽象路径名的 file: URI。

三、字节流

输入流:

//字节流
    @Test
    public void test02(){
        File file=new File("file\test.txt");
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        InputStream is=null;
        try{
            is=new FileInputStream(file);//创建一个输入字节流
        int nr;
        while((nr=is.read())!=-1){//每次从文件中读出一个字节
            baos.write(nr);//将读出的字节,写入一个字节数组缓冲流
        }
        baos.flush();//刷新,强制写入
        byte[] bytes=baos.toByteArray();
        String str=new String(bytes);
        System.out.println(str);
        
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try {
                if(baos!=null){
                    baos.close();
                }
                if(is!=null){
                    is.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
    }

输出流:

//字节流
    @Test
    public void test01() {
        String say="hello world";
        byte[] bys=say.getBytes();//将要写入的字符串,变为字节数组
        File file=new File("file");
        //判断目录是否存在,不存在创建目录
        if(!file.exists()){
            file.mkdir();
        }
        File txtfile=new File("file\test.txt");
        //判断文件是否存在,不存在创建文件
        if(!txtfile.exists()){
            try {
                txtfile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        OutputStream os=null;
        try {
            os = new FileOutputStream(txtfile);//创建一个字节输出流数据
            os.write(bys);//将字节数组写入文件
            os.flush();//刷新字节流缓冲区,强制写入文件
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(os != null){
                    os.close();//释放字节流对象资源
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }    
    }

综合:

//字节流,输入并输出
    @Test
    public void test03(){
        File sourceFile=new File("");
        File targetFile=new File("");
        InputStream is=null;
        OutputStream os=null;
        byte[] bys=new byte[1024];//一个字节数组用于存放读出的字节
        int len;
        try{
            is=new FileInputStream(sourceFile);//创建一个字节输入流
            os=new FileOutputStream(targetFile);//创建一个字节输出流
            while((len=is.read(bys))!=-1){//一次读入多个字节储存在bys字节数组中,len为本次读取的字节数
                os.write(bys, 0, len);//设置偏移值,一次可以写入多个字节
            }
            os.flush();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            
            
            try {
                if(is!=null){
                    is.close();
                }
                if(os!=null){
                    os.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

四、字符流

提供了两个操作字符流的父类

java.io.Reader   ---   字符输入流

|- InputStreamReader

  |- FileReader 操作字符便捷类

|- BufferedReader

java.io.Writer

|- OutpustStreamWriter

  |- FileWriter 操作字符便捷类

|- BufferedWriter

1.字符流

//字符流 输入
    @Test
    public void test05(){
        File file=new File("file\test.txt");
        try {
            InputStream is=new FileInputStream(file);//创建一个字节流对象
            //InputStreamReader构造函数将传入的字节流转化为字符流,并且可以设置编码方式
            InputStreamReader isr=new InputStreamReader(is,"UTF-8");
            int len;
            StringBuffer sb=new StringBuffer();
            while((len=isr.read())!=-1){//isr.read()返回读取到字符相应的int值,每次读取一个字符
                sb.append((char)len);
            }
            System.out.println(sb);
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
//字符流 输出
    @Test
    public void test04(){
        String say ="hello 你们好";
        OutputStream os=null;
        OutputStreamWriter osw=null;
        try {
            os=new FileOutputStream("file\test.txt",true);//创建一个字节流对象
            //OutputStreamWriter构造函数将传入的字节流转化为字符流,并且可以设置编码方式
            osw=new OutputStreamWriter(os,"UTF-8");
            osw.write(say);
            osw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(osw!=null){
                    osw.close();
                }
                if(os!=null){
                    os.close();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
    }

2.字符缓冲流(效率高些)

//BufferWriter输出
    @Test
    public void test06() throws IOException{
        File file=new File("file\test.txt");
        OutputStream os=new FileOutputStream(file);
        //将字节流转换为字符流
        Writer osw=new OutputStreamWriter(os);
        //将字符流转换为字符缓冲流————创建缓冲字符流
        BufferedWriter bw=new BufferedWriter(osw);
        bw.write("
 hello");
        bw.flush();
        bw.close();
    }
//BufferReader
    @Test
    public void test07() throws IOException{
        File file=new File("file\test.txt");
        InputStream is=new FileInputStream(file);
        //将字节流转换为字符流
        Reader isr=new InputStreamReader(is);
        //将字符流转换为字符缓冲流————创建缓冲字符流
        BufferedReader br=new BufferedReader(isr);
        StringBuffer sb=new StringBuffer();
        String str;
        while((str=br.readLine())!=null){//一行一行的读入
            sb.append(str);
            sb.append("
");
        }
        System.out.println(sb);
        br.close();
    }

3.便捷类(无法设置编码格式)

//FileWriter
    @Test
    public void test08() throws IOException{
        File file=new File("file\test.txt");
        FileWriter fw=new FileWriter(file);
        fw.write("
 hello");
        fw.flush();
        fw.close();
    }
//FileReader
    @Test
    public void test09() throws IOException{
        File file=new File("file\test.txt");
        FileReader fr=new FileReader(file);
        StringBuffer sb=new StringBuffer();
        int str;
        while((str=fr.read())!=-1)
        {
            sb.append((char)str);
        }
        System.out.println(sb.toString());
        fr.close();
    }