JavaEE

java IO流,文件

2019-01-26  本文已影响1657人  会摄影的程序员

1. IO 流

1.1 根据流的流向分类

  1. Input 输入流
  2. Output 输出流

1.2 根据流操作的数据来分类

  1. 字符流: 操作字符
    只能操作普通文本文件
  2. 字节流:操作字节
    能操作一切文件

1.3 java中的四大流

  1. 字符输入流

    1. 父类:Reader
      1. FileReader
      2. BufferedReader
    2. 功能: 读取一个字符,读取一个字符数组
  2. 字符输出流

    1. 父类:Write
      1. FileWrite
      2. BufferedWrite
    2. 功能:写一个字符,写一个字符数组,字符串
  3. 字节输入流

    1. 父类:InputStream
      1. FileInputStream
      2. BufferedInputStream
    2. 功能:读取一个字节,读取一个字节数组
  4. 字节输出流

    1. 父类:OutputStream
      1. FileOutputStream
      2. BufferedOutputStream
    2. 功能:写一个字节,写一个字节数组
  5. 规律
    只要是输入流 此流方法名一定叫read
    只要是输出流 此流方法名一定叫write

java中的流命名规范;
功能+父类的名字

2 OutputStream

字节输出流的根类,是一个抽象类

  1. void close();
    关闭流

  2. void flush();
    刷新流

  3. void write(int b);
    写一个字节

  4. void write(byte[] bs);
    写一个字节数组

  5. void write(byte[] bs, int startIndex, int lenght);
    写一个字节数组的一部分

2.1 构造

  1. FileOutPutStream(String filename)
    不可以续写
  2. FileOutPutStream(String filename,boolean flag)
    可以续写
  3. FileOutPutStream(File file,boolean flag)

2.2 使用

demo:

public void outputStreamdemo() throws IOException {
    //创建数据流
    FileOutputStream fileOutputStream = new FileOutputStream("2.txt",true);
    //写数据

    fileOutputStream.write("hello".getBytes());

    //关闭数据流
    fileOutputStream.close();
}

3 InputStream

字节输入流的根类,是一个抽象类

  1. void close();
    关闭流
  2. int read();
    读取一个字节,返回的是ASSIC码
  3. int read(byte[] bs);
    读取一个字节数组,读出的数据是传入的,返回实际读出的数量

3.1 构造

  1. FileInputStream

3.2 使用

demo:

    public void inputStreamDemo() throws IOException{
        FileInputStream fileInputStream = new FileInputStream("2.txt");

        //一个个读
        int b = 0;
        while ((b = fileInputStream.read()) != -1){
            System.out.print((char)b);
        }

        fileInputStream.close();
    }

    public void inputStreamDemo2() throws IOException{
        FileInputStream fileInputStream = new FileInputStream("2.txt");

        //一次读一个数组
        int tempLen = 0;
        byte[] bs = new byte[4];
        while ((tempLen=fileInputStream.read(bs))!=-1){
            String s = new String(bs,0,tempLen);
            System.out.print(s);
        }

        fileInputStream.close();
    }

复制文件

public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        String inputSrc = "C:\\Users\\81022\\Downloads\\copyFile\\原始文件\\无标题.png";
        String outputSrc = "C:\\Users\\81022\\Downloads\\copyFile\\目标文件夹\\test.png";
        //创建两个流
        FileInputStream fileInputStream = new FileInputStream(inputSrc);
        FileOutputStream fileOutputStream = new FileOutputStream(outputSrc,true);

        //复制
        //一次读一个字节  太慢
        /*int b = 0;
        while ((b=fileInputStream.read())!=-1){
            fileOutputStream.write(b);
        }*/

        byte[] bs = new byte[1024];
        int len = 0;
        while ((len=fileInputStream.read(bs))!=-1){
            fileOutputStream.write(bs,0,len);
        }


        //关流
        fileInputStream.close();
        fileOutputStream.close();

    }
}

4 缓冲流

相比没有换成功流,效率更高

4.2 BufferedOutputStream 缓冲输出流

  1. 创建
     BufferedOutputStream bufOutputStr = new BufferedOutputStream(new FileOutputStream(outSrc));
    
  2. 方法
        //写一个字节
        bufOutputStr.write(11);
        //写一个字节数组
        bufOutputStr.write("test".getBytes());
        //写一个字符串
        byte[] bs= new byte[10];
        bs = "你好!!!".getBytes();
        bufOutputStr.write(bs);
        bufOutputStr.write(bs,0,2);
    

4.1 BufferedInputStream 缓冲输入流

  1. 创建
     BufferedInputStream bufdInputStr = new BufferedInputStream(new FileInputStream(inSrc));
    
  2. 方法
        int n = 0;
        while ((n = bufdInputStr.read())!=-1){
            System.out.print((char)n);
        }
    
    
        //读一个字符串
        byte[] bs = new byte[10];
        int len = 0;
        String s;
        while ((len = bufdInputStr2.read(bs))!=-1){
            s= new String(bs,0,len);
            System.out.print(s);
        }
    

5 字符流

使用字节流读中文会出现乱码

5.1 FileReader

和字节流差不多

5.2 BufferedReader

和字节流差不多
多了一个 readLine();

5.3 FileWrite

和字节流差不多
多了写字符串的功能

5.4 BufferWrite

和字节流差不多
多一个newLine()

demo:

    @Test
    public void ReaderDemo1() throws IOException {
        FileReader fileReader = new FileReader(new File("fileTest.txt"));
        int n = 0;
        while ((n=fileReader.read())!=-1){
            System.out.print((char)n);
        }

        fileReader.close();
    }

    @Test
    public void ReaderDemo2() throws IOException {
        FileReader fileReader = new FileReader("fileTest.txt");

        int len = 0;
        char[] cr = new char[10];
        while ((len = fileReader.read(cr))!=-1){
            System.out.print(cr);
        }

        fileReader.close();
    }

    @Test
    public void RederDemo3() throws IOException{
        BufferedReader bfReader = new BufferedReader(new FileReader("fileTest.txt"));

        String s;
        while ((s = bfReader.readLine())!=null){
            System.out.println(s);
        }

        bfReader.close();
    }



    @Test
    public void RederDemo4() throws IOException{
        FileWriter fr = new FileWriter("fileTest.txt");
        fr.write("这里是测试写入");
        fr.close();
    }


    @Test
    public void RederDemo5() throws IOException{
        BufferedWriter br = new BufferedWriter(new FileWriter("fileTest.txt",true));

        br.newLine();
        br.write("sdfsfd");
        br.close();
    }

文件归类demo:

    import net.sf.json.JSONObject;
    
    import java.io.*;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.Set;
    
    /**
     * @author chenPeng
     * @version 1.0.0
     * @ClassName MoveFile.java
     * @Description TODO
     * @createTime 2019年01月26日 15:41:00
     */
    public class MoveFile {
        static String src;
        static String toSrc;
        static Set<Map.Entry<String,String>> fenLei;
        static JSONObject json;
    
    
        public static void init() throws IOException{
            File directory = new File("");
            BufferedReader fileReader = new BufferedReader(new FileReader(directory.getAbsoluteFile()+"/config.json"));
            StringBuffer strBuf = new StringBuffer();
            String temp;
            while ((temp = fileReader.readLine())!=null){
                System.out.println(temp);
                strBuf.append(temp);
            }
    
            fileReader.close();
    
            json = JSONObject.fromObject(strBuf.toString());
            //获取连接
            JSONObject srcJson = json.getJSONObject("路径");
            src = (String) srcJson.get("原始路径");
            toSrc = (String) srcJson.get("目标路径");
    
            fenLei = json.getJSONObject("分类").entrySet();
        }
    
        /**
         * 入口
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:24
         * @Param [args]
         * @return void
         **/
        public static void main(String[] args) throws IOException {
            init();
            File files = new File(src);
            getPath(files.listFiles());
    
            System.out.println("是否删除原文件!!!");
            System.out.println("1 为删除 否则按其他");
            Scanner scanner = new Scanner(System.in);
            String str = scanner.next();
            if ("1".equals(str)){
                System.out.println("正在删除...");
                removeFile(files.listFiles());
            }
    
        }
    
        /**
         * 删除文件
         * @Author chenpeng
         * @Description //TODO
         * @Date 22:20
         * @Param [files]
         * @return void
         **/
        public static void removeFile(File[] files) throws IOException{
            for (File file : files) {
                if (file.isFile()){
                    file.delete();
                }else{
                    if (!file.delete()){
                        removeFile(file.listFiles());
                        file.delete();
                    }
                }
            }
        }
    
        /**
         * 得到路径 分析是文件还是文件夹
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:24
         * @Param [files]
         * @return void
         **/
        public static void getPath(File[] files) throws IOException {
            for (File file : files) {
                if (file.isFile()){
                    classification(file);
                }else{
                    copyDir(file.listFiles(),file.getName());
                }
            }
        }
    
    
        /**
         * 递归复制文件
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:24
         * @Param [files]
         * @return void
         **/
        public static void copyDir(File[] files, String name) throws IOException {
            //如果不存在就先建立文件夹
            String gotoSrc = toSrc+"/文件夹/"+name;
            isHave(gotoSrc);
    
            //复制文件
            for (File file : files) {
                if (file.isFile()){
                    copy(file,gotoSrc);
                }else{
                    copyDir(file.listFiles(), name+"/"+file.getName());
                }
            }
        }
    
        /**
         * 复制文件
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:25
         * @Param [file]
         * @return void
         **/
        public static void copy(File file,String src) throws IOException {
    
            System.out.println(file.getAbsolutePath());
            System.out.println("复制到");
            System.out.println(src);
            System.out.println("==============开始执行==============");
    
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(src+file.getName()));
    
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = fis.read(bs))!=-1){
                fos.write(bs,0,len);
            }
    
            fos.close();
            fis.close();
    
            System.out.println("==============执行结束==============");
            System.out.println();
        }
    
        /**
         * 分发文件
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:25
         * @Param [file]
         * @return void
         **/
        public static void classification(File file) throws IOException {
            String fileName = file.getName();
            String toUrl="";
    
            String[] fName = fileName.split("\\.");
            String endName = "."+fName[(fName.length-1)];
            System.out.println("=========================================================="+endName);
    
    
            for (Map.Entry<String, String> stringEntry : fenLei) {
                String strKye = stringEntry.getKey();
    
                JSONObject leiBie = json.getJSONObject("分类").getJSONObject(strKye);
                if (leiBie.containsValue(endName)){
                    toUrl = toSrc+"/"+strKye+"/";
                }
            }
    
    
            if ("".equals(toUrl)){
                toUrl = toSrc+"/其他文件/";
            }
            isHave(toUrl);
            copy(file,toUrl);
    
        }
    
        /**
         * 是否存在,不存在建立文件夹
         * @Author chenpeng
         * @Description //TODO
         * @Date 16:59
         * @Param [srcs]
         * @return void
         **/
        public static void isHave(String srcs){
            File gotoFile = new File(srcs);
            if (!gotoFile.exists()){
                gotoFile.mkdirs();
            }
        }
    
    
    }

配置文件

{
  "路径":{
    "原始路径":"C:\\Users\\81022\\Downloads",
    "目标路径":"F:\\普通文档\\归档"
  },
  "分类":{
    "文本": {
      "txt": ".txt",
      "docx": ".docx",
      "doc": ".doc",
      "xls": ".xls",
      "xlsx": ".xlsx",
      "ppt": ".ppt",
      "pptx": ".pptx"
    },
    "视频": {
      "mp4": ".mp4",
      "mov": ".mov"
    },
    "代码文件": {
      "sql": ".sql",
      "war": ".war",
      "class": ".class",
      "jar": ".jar"
    },
    "图片": {
      "psd": ".psd",
      "jpg": ".jpg",
      "png": ".png"
    },
    "压缩包": {
      "zip": ".zip",
      "rar": ".rar",
      "7z": ".7z",
      "tar":".tar",
      "gz": ".gz"
    },
    "可执行文件": {
      "exe": ".exe",
      "msi": ".msi"
    }
  }
}

上一篇下一篇

猜你喜欢

热点阅读