zoukankan      html  css  js  c++  java
  • Java IO流

    1、站在内存的角度看待方向,从其他设备进入内存的,都是输入,从内存到其他设备的,都是输出

      I/O就是用于设备之间进行数据交互的对象所属的类型

    2、java中操作设备设备之间数据传输的对象,都是IO流对象,这些对象所属的类型,都在io包中

    3、按照流向分为输入流和输出流

      输入流:其它设备到内存的流对象   进行读取

      输出流:内存流到其它设备的流对象   进行写出

    4、按照功能分为字节流和字符流

      字节流:直接操作字节的流对象

      字符流:直接操作字符的流对象  字符流 = 字节流+编码格式

    5、字节流:

      输入(读取):InputStream  使用子类操作 FileInputStream(File file)   FileInputStream(String path)

        read()一个个字节读取   read(byte[] b)一个个读取字节到数组,返回数组

      输出(写入):OutputStream  使用子类操作 FileOutputStream(File file)  FileInputStream(String path) 

         writer()一个个字节写入  writer(byte[] b)

    6、字符流:使用字节流可以操作字符,但字符长度不一致时会产生乱码。注:字符流无法操作非纯文本文件

      输入(读取):Reader    使用子类操作 FileReader(File file)  FileReader(String path)

        方法同字节流,用来处理不是一个字符长度的的字符文件  高效缓冲流多一个readLine()一次读取一行

      输出(写入):Writer     使用子类操作 FileWriter(File file)  FileWriter(String path)

        方法同字节流,但高效缓冲流有特有方法newLine() 用来写换行符,解决各个系统换行符不同问题

     

    import java.io.FileInputStream;
    
    public class test1 {
    
        public static void main(String[] args) throws Exception {
            FileInputStream fis = new FileInputStream("test.txt");
            int i=0;
            byte[] b = new byte[2];
            while((i=fis.read(b))!=-1) {
                System.out.println(new String(b,0,i));
            }        
        }
    }
    字节流读纯汉字文本

     

    7、在使用流操作之前,应进行导包,io包,在操作时应解决异常,操作完毕后应关闭资源

    8、高效缓冲流 BufferedInputStream和BufferedOutputStream

      1、采用装修设计模式,对某个类的功能进行增强(且不用继承该类,将该类的一个对象传入该类)

      2、原理:该类型提供了一个8192字节的数组,当外界调用read()方法时,一次性的读取8192个字节到数组中,对象再次调用时就不需要访问磁盘。写入时也直接写进数组,等8192字节写满后,一次性写入,不需要一直写入磁盘,如果没有写满,在关闭流对象时也会写入磁盘。

    public class Test2 {
    
        public static void main(String[] args) {
            // 装修设计模式
            Man m = new Man();
            SuperMan superman = new SuperMan(m);
            superman.fly();
    
        }
    
    }
    class Man{
        public void run() {
            System.out.println("i can run");
        }
    }
    class SuperMan{
        Man man = null;
        public SuperMan(Man man) {
            this.man = man;
        }
        public void run() {
            man.run();
            System.out.println("i can fly");
        }
    }
    装修设计模式

    9、close()和flush()

      close()方法使用时会先调用flush()方法

      流对象一旦使用close()关闭,则无法继续使用

      flush()只是将缓冲区的数据刷新到相应的文件,不会关闭流对象,字节流会自动刷新,字符流则需要手动刷新

    10、练习

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class MoniRead {
    
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            MyInputStream m = new MyInputStream("aa.txt");
            byte[] b = new byte[2];
            int len=0;
            while((len=m.myRead(b))!=-1) {
                System.out.println(new String(b,0,len));
            }
            
        }
    
    }
    class MyInputStream{
        
        private File f;
        private FileInputStream f1;
        public MyInputStream(String s) throws FileNotFoundException {
            f = new File(s);
            if(!f.exists()) {
                FileNotFoundException e = new FileNotFoundException();
                throw e;
            }
            f1 = new FileInputStream(f);
        }
        public MyInputStream(File f) throws FileNotFoundException {
            if(!f.exists()) {
                FileNotFoundException e = new FileNotFoundException();
                throw e;
            }
            f1 = new FileInputStream(f);
        }
        //    read(byte[] b)   int 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
        public int myRead(byte[] b) throws IOException {    
            int i=0;
            int len=0;
            while(len<b.length&&(i=f1.read())!=-1) {
                b[len]=(byte)i;
                len++;
            }
            return len;
        }
    
        //    read()  从输入流中读取数据的下一个字节。 int
        public int myRead() throws IOException {
            return f1.read();
        }
    }
    模拟read()
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class MoniReader {
    
        public static void main(String[] args) throws Exception {
            File f = new File("aa.txt");
            FileReader fr = new FileReader(f);
            MyBufferedReader mbr = new MyBufferedReader(fr);
            String line=null;
            while((line = mbr.myReadLine())!=null) {
                System.out.println(line);
            }
        }
    
    }
    class MyBufferedReader{
        private BufferedReader br ;
    
        public MyBufferedReader(FileReader f){
            br = new BufferedReader(f);
        }
        
        public String myReadLine() throws IOException {
            int i=0;
            StringBuilder s = new StringBuilder();
            while((i=br.read())!=-1&&(char)i!='
    ') {
                if((char)i=='
    ') {continue;}
                    s.append((char)i);    
            }
            if(s.length()==0) {
                return null;
            }
            return s.toString();
        }
    }
    模拟reader
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.Scanner;
    
    /*
     * 键盘录入一个文件夹路径,作为源文件夹;键盘录入一个文件夹路径,作为目标文件夹
        写代码将源文件夹拷贝到目标文件夹中
     */
    public class Test {
    
        public static void main(String[] args) throws Exception {
            File src = getFile();//获取源文件
            File des = getFile();//获取目标文件
            copy(src,des);//进行复制
    
        }
    
        private static void copy(File src, File des) throws Exception {
            File newSrc = new File(des,src.getName());//在目标文件中新建与源文件同名的文件夹
            newSrc.mkdir();
            File[] listFiles = src.listFiles();
            if(listFiles!=null) {
                for(File subFile:listFiles) {
                    if(subFile.isDirectory()) {
                        copy(subFile,newSrc);//如果子文件是文件夹,递归调用本方法
                    }else {
                        File desFile = new File(newSrc,subFile.getName());//创建想要复制的文件
                        FileInputStream fis = new FileInputStream(subFile);//将源文件关联
                        BufferedInputStream bis = new BufferedInputStream(fis);//封装增强
                        FileOutputStream fos = new FileOutputStream(desFile);//目标文件关联
                        BufferedOutputStream bos = new BufferedOutputStream(fos);//封装增强
                        int b;
                        while((b=bis.read())!=-1) {
                            bos.write(b);
                        }
                        bos.close();
                        bis.close();
                    }
                }
            }
            
        }
    
        private static File getFile() {
            Scanner sc = new Scanner(System.in);
            while(true) {
                String s = sc.nextLine();
                File file = new File(s);
                if(file.isDirectory()) {
                    return file;
                }else {
                    System.out.println("非法录入");
                }
            }
        }
        
    }
    练习文件夹拷贝
    import java.io.File;
    import java.util.Scanner;
    
    //1、键盘录入一个文件夹路径,删除该文件夹(包含文件夹内容)
    public class Test {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String s = sc.nextLine();
            File file = new File(s);
            deleteFile(file);
            
        }
        public static void deleteFile(File file) {        
            if(file.exists()) {
                File[] listFiles = file.listFiles();
                if(null==listFiles||listFiles.length==0) {
                    file.delete();
                    return;
                }
                for(File f:listFiles) {
                    deleteFile(f);
                }
                file.delete();
            }
            
        }
    }
    File类和递归的使用
    import java.io.File;
    import java.util.Scanner;
    
    //递归实现输入任意目录,列出文件以及文件夹
    public class Test2 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            while(true) {
                printAll(getFile());
                System.out.println("是否继续?继续请输入1,退出请输入0");
                Scanner sc = new Scanner(System.in);
                int i = sc.nextInt();
                if(i==1) {
                    continue;
                }else {
                    break;
                }
            }
        }
        public static File getFile() {
            Scanner sc = new Scanner(System.in);
            while(true) {
                System.out.println("请输入想要查询的文件路径");
                String s = sc.nextLine();
                File file = new File(s);
                if(file.exists()) {
                    return file;
                }else {
                    System.out.println("请重新输入");
                }
            }
        }
        public static void printAll(File file) {
            System.out.println(file.getName());
            if(file.isDirectory()) {
                File[] listFiles = file.listFiles();
                for(File subFile:listFiles) {
                    printAll(subFile);
                }
            }
        }
    }
    递归和File类练习二
    //对拷贝的效率进行查询,可以测试高效缓冲流的效率
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.util.Scanner;
    
    public class Demo03 {
    
        public static void main(String[] args) throws Exception  {
            // TODO Auto-generated method stub
            File dsc = getFile();
            File src = getFile();
            FileInputStream f1 = new FileInputStream(src);
            BufferedInputStream bis  = new BufferedInputStream(f1);
            if(!dsc.exists()) {
                dsc.createNewFile();
            }
            FileOutputStream f2 = new FileOutputStream(dsc);
            BufferedOutputStream bos = new BufferedOutputStream(f2);
            byte[] b = new byte[1024];
            int len=0;
            long startTime = System.currentTimeMillis();
            while((len=bis.read(b))!=-1) {
                bos.write(b);
                double d = dsc.length();
                System.out.printf("文件已经复制了%.2f%%
    ",d*100/src.length());
            }
            long endTime = System.currentTimeMillis();
            System.out.println("总共用时"+(endTime-startTime)/1000.000+"秒");
            bos.close();
            bis.close();
        }
        public static File getFile() {
            Scanner sc = new Scanner(System.in);
            while(true) {
                System.out.println("请输入想要查询的文件路径");
                String s = sc.nextLine();
                File file = new File(s);
                if(file.exists()) {
                    return file;
                }else {
                    System.out.println("请重新输入");
                }
            }
        }
    
    }
    高效缓冲流效率体验
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Scanner;
    
    public class Test{
    
        public static void main(String[] args) throws IOException {
            InputStream is = System.in;
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            
            Scanner sc = new Scanner(System.in);
            
        }
    }
    System.in的原理
    /*
     * 键盘录入一个文件路径,将该文件反转
        反转:第一行变成最后一行,第二行变成倒数第二行
     */
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.util.LinkedList;
    import java.util.List;
    
    public class Demo04 {
    
        public static void main(String[] args) throws Exception {
            File file = new File("aa.txt");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            File file2 = new File("bb.txt");
            FileWriter fw = new FileWriter(file2);
            BufferedWriter bw = new BufferedWriter(fw);
            LinkedList<String> list = new LinkedList<>();
            String str = null;
            while((str=br.readLine())!=null) {
                list.addFirst(str);
            }
            while(list.size()>0) {
                bw.write(list.removeFirst());
                bw.newLine();
                bw.flush();
            }
            bw.close();
            br.close();
        }
    
    }
    文件内容反转练习

     

  • 相关阅读:
    SmartBusinessDevFramework架构设计-1:结构简介
    C# 注销掉事件,解决多播委托链表的问题
    #import 无法打开源文件msado.tlh
    【MFC】OnInitDialog
    m_pRecordset->Open
    加L“”
    error C2065: “m_Pic”: 未声明的标识符
    存储过程不返回记录集导致ADO程序出错
    关于BSTR数据类型
    定义的函数在main中调用时提示找不到标识符
  • 原文地址:https://www.cnblogs.com/xfdhh/p/11220598.html
Copyright © 2011-2022 走看看