利用spring的Resource接口实现文件的读写

Resource 继承 InputStreamSource 抽象了 spring内部所有使用到的底层资源
常用间接的子类 ClassPathResource FileSystemResource ByteArrayResource 等

package com.huayang;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static void main(String args[]) throws IOException {

        Resource resource = new FileSystemResource("/Users/szy/worksapce/springlearning/src/main/resources/1.txt");
        InputStream is = resource.getInputStream();
        File file = new File("/Users/szy/worksapce/springlearning/src/main/resources/2.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file);
        int from = 0;
        int len;
        byte[] bytes = new byte[1024];
        while ((len = is.read(bytes)) != -1) {
            out.write(bytes, from, len);
            from = len + from;
        }
        out.close();
        is.close();
    }
}



猜你喜欢

转载自young-2017.iteye.com/blog/2373033