欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java IO流练习:文件复制、遍历子目录、复制所有子目录

程序员文章站 2022-06-16 13:34:41
...
import org.junit.Test;

import java.awt.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;

/**
 * @author king
 *         Created by king on 2017/5/19.
 */
public class IOTrain {
    //    @Test
    public void testTime() {//测试函数运行时间
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("s");
        System.out.println(sdf.format(end - start));
    }

    //    @Test
    public void createFile() {//创建a.txt
        File file = new File("D:\\file\\a.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    @Test
    public void fileList() {//列出D盘下的所有文件、文件夹
        File file = new File("D:");
        String[] ss = file.list();
        for (String s : ss) System.out.println(s);
    }

    //    @Test
    public void fileList2() {//列出D盘下的所有文件、文件夹
        File file = new File("D:");
        File[] files = file.listFiles();
        for (File f : files) System.out.println(f.getPath());
    }

    //    @Test
    public void makeDir() {//创建文件夹
        File file = new File("D:\\file\\44");
        file.mkdir();
    }


    //    @Test
    public void testShowAllDir() {//显示D盘下所有的子文件
        String path = "D:";
        showAllDir(path);
    }

    public void showAllDir(String path) {
        File file = new File(path);
        File fs[] = file.listFiles();
        for (int i = 0; i < fs.length; i++) {
            if (fs[i].isDirectory()) {
                try {
                    showAllDir(fs[i].getAbsolutePath());
                } catch (Exception e) {
                }
            } else {
                System.out.println(fs[i].getAbsolutePath());
            }
        }
    }

    //    @Test
    public void browseBaidu1() {//用浏览器打开百度
        try {
            URI uri = new URI("http://www.baidu.com");
            Desktop.getDesktop().browse(uri);
        } catch (Exception e) {
        }
    }

    //    @Test
    public void browseBaidu2() {//用浏览器打开百度,完整版
        String webSite = "http://www.baidu.com";
        Desktop desktop = Desktop.getDesktop();
        if (Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) {
            URI uri = null;
            try {
                uri = new URI(webSite);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            try {
                desktop.browse(uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //    @Test
    public void readByte() {// 从文件系统中的某个文件中获得输入字节
        try (FileInputStream fs = new FileInputStream("D:\\file\\1.txt")) {
            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = fs.read(buffer)) != -1) {
                System.out.println(new String(buffer));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void writeByte() {//FileOutputStream,意为文件输出流,是用于将数据写入File或 FileDescriptor的输出流。
        try (FileOutputStream fs = new FileOutputStream("D:\\file\\3.txt")) {
            fs.write("哈尔滨".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //    @Test
    public void copyByte() {//将1.txt拷贝到2.txt
        try (FileOutputStream w = new FileOutputStream("D:\\file\\2.txt");
             FileInputStream r = new FileInputStream("D:\\file\\1.txt")) {
            byte[] buffer = new byte[1024];
            int n = 0;
            while ((n = r.read(buffer)) != -1) {
                w.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    @Test
    public void readChar() {//FileReader类从InputStreamReader类继承而来。该类按字符读取流中数据。
        try (Reader reader = new FileReader("D:\\file\\1.txt")) {
            char[] buffer = new char[20];
            int n = 0;
            while ((n = reader.read(buffer)) != -1) {
                System.out.println(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    @Test
    public void writeChar() {//FileWriter类从OutputStreamReader类继承而来。该类按字符向流中写入数据。
        try (Writer writer = new FileWriter("D:\\file\\1.txt")) {
            writer.write("哈尔滨");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    @Test
    public void copyChar() {//按字符流将1.txt复制给2.txt
        try (FileReader reader = new FileReader("D:\\file\\1.txt");
             FileWriter writer = new FileWriter("D:\\file\\2.txt")) {
            int n = 0;
            char[] buffer = new char[20];
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    @Test
    public void FindFileByType() {//查找 *.bat
        File file = new File("D:");
        File[] find = file.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".bat");
            }
        });
        for (File f : find) System.out.println(f.getName());
    }

    //    @Test
    public void testCopyAllDir1() {
        String readPath = "D:\\file";//源地址
        String writePath = "D:\\file2";//目标地址
        new File(writePath).mkdirs();
        copyAllDir1(readPath, writePath);
    }

    public void copyAllDir1(String readPath, String writePath) {
        File file = new File(readPath);
        File[] fs = file.listFiles();
        for (int i = 0; i < fs.length; i++) {
            try {
                if (fs[i].isDirectory()) {
                    fs[i].mkdir();
                    copyAllDir1(fs[i].getAbsolutePath(), writePath + "\\" + fs[i].getName());
                } else {
                    System.out.println(fs[i].getAbsolutePath());
                }
            } catch (Exception e) {
            }
        }
    }

    //    @Test
    public void testCopyAllDir2() {
        String readPath = "D:\\file";//源地址
        String writePath = "D:\\file2";//目标地址
        new File(writePath).mkdir();
        copyAllDir2(readPath, writePath);
    }

    public void copyAllDir2(String readPath, String writePath) {//将readPath中的所有子文件拷贝到writePath目录下。
        //获取当前readPath目录下所有文件、文件夹,并存在fs[] 中
        File file = new File(readPath);
        File fs[] = file.listFiles();

        //fs!=null 排除空指针异常
        if (fs != null) {
            //遍历当前目录
            for (int i = 0; i < fs.length; i++) {
                //如果当前对象fs[i]是文件夹,则在目标地址中创建同名的文件夹。
                if (fs[i].isDirectory()) {
                    new File(writePath + "\\" + fs[i].getName()).mkdir();
                    copyAllDir2(fs[i].getPath(), writePath + "\\" + fs[i].getName());
                }

                //如果当前对象fs[i]是文件,那么按字节拷贝到目标地址。
                else {
                    try (FileInputStream readFile = new FileInputStream(fs[i].getPath());/*从这里读数据*/
                         FileOutputStream writeFile = new FileOutputStream(writePath + "\\" + fs[i].getName()))/*往这里写数据*/ {
                        byte[] buffer = new byte[1024];
                        int n = 0;
                        while ((n = readFile.read(buffer)) != -1) {
                            writeFile.write(buffer, 0, n);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


//    @Test
    public void mergeRandomAccessFile() {//将两个mp3文件合并。RandomAccessFile的唯一父类是Object
        try (RandomAccessFile r = new RandomAccessFile("c://1.mp3", "r");
             RandomAccessFile w = new RandomAccessFile("c://2.mp3", "rw")) {
            byte[] buffer = new byte[1024 * 1024];
            w.seek(1024 * 1024);//定位到末尾,MP3 avi
            int n = 0;
            while ((n = r.read(buffer)) != -1) {
                w.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Test
    public void copyRandomAccessFile() {//复制文件。RandomAccessFile已经被JDK1.4的nio的"内存映射文件(memory-mapped files)"给取代了。
        try (RandomAccessFile r = new RandomAccessFile("c://1.wmv", "r");
             RandomAccessFile w = new RandomAccessFile("d://2.wmv", "rw")) {
            byte[] buffer = new byte[1024 * 1024];
            int n = 0;
            while ((n = r.read(buffer)) != -1) {
                w.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @Test
    public void divideRandomAccessFile(){//将1.txt分割为多个
        try(RandomAccessFile r=new RandomAccessFile("D:\\file\\1.txt","r")){
            byte[] buffer=new byte[2];
            int n=0;
            int i=1;
            while((n=r.read(buffer))!=-1){
                RandomAccessFile w=new RandomAccessFile("D:\\file\\1_"+(i++)+".txt","rw");
                w.write(buffer,0,n);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void mergeFile(){//将多个1_?.txt文件合并为一个1.txt文件
        File file=null;
        try(RandomAccessFile w=new RandomAccessFile("D:\\file\\1.txt","rw")){
            int i=1;
            while((file=new File("D:\\file\\1_"+(i++)+".txt")).exists()){
                RandomAccessFile r=new RandomAccessFile(file,"r");
                copyTo(r,w);
            }
        }catch(IOException e){e.printStackTrace();}
    }

    private void copyTo(RandomAccessFile r, RandomAccessFile w) throws IOException {
        byte[] buffer=new byte[8];
        int n=0;
        while((n=r.read(buffer))!=-1){
            w.write(buffer,0,n);
        }
    }
}
相关标签: java io流