文件IO操作

79 阅读1分钟
package com.qjmy.sxxy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.*;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class DemoControllerTest {


    @Test
    public void writeFile() throws IOException {

//        String hello = new String("Hello world1111111!");
//        byte[] byteArray = hello.getBytes();
//        File file = new File("D:/test.txt");
//        OutputStream os = new FileOutputStream(file);
//        os.write(byteArray);
//        os.flush();
//        os.close();

        //创建文件输入流对象
        FileInputStream fis = new FileInputStream("d:/test.txt");
        //创建文件输出流对象
        FileOutputStream fos = new FileOutputStream("d:/test2.txt", true);
        //定义缓冲区大小
        byte[] b = new byte[512];
        //记录每次读取的字节
        int len;
        //拷贝文件前的系统时间
        long begin = System.currentTimeMillis();
        //读取文件并判断是否到达文件末尾
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len);
        }
        //拷贝文件后的时间
        long end = System.currentTimeMillis();
        System.out.println("拷贝文件时间:" + (end - begin) + "毫秒");
        fos.close();
        fis.close();

    }

    @Test
    public void readFile() throws IOException {

        File file = new File("D:/test.txt");
        byte[] byteArray = new byte[(int) file.length()];

        InputStream is = new FileInputStream(file);

        int size = is.read(byteArray);

        System.out.println("大小:" + size + ";内容:" + new String(byteArray));

        is.close();
    }

    @Test
    public void dirFile() {

        File file = new File("D:/redis2");

//        if (file.isDirectory()) {
//            String[] fileNames = file.list();
//            for (String fileName : fileNames) {
//                System.out.println(fileName);
//            }
//        }

        files(file);
    }

    public void files(File file) {
        File[] files = file.listFiles();

        for (File f : files) {
            if (f.isDirectory()) {
                files(f);
            }
            System.out.println(f.getAbsolutePath());
        }
    }


}

zhuanlan.zhihu.com/p/574292062