读取根路径下文件数据读取文件

SpringBoot核心

读取顺序
(1)与jar同级的config文件夹内
(2)与jar同级的文件夹
(3)读取jar包内的resources目录


import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Component
public class FileLoader ...

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 读取顺序:
     * (1)与jar同级的config文件夹内
     * (2)与jar同级的文件夹
     * (3)读取jar包内的resources目录
     */
    public InputStream getResource(String fileName) {

        Resource resource = resourceLoader.getResource("file:config/" + fileName);
        if (resource.exists()) {
            LOGGER.debug("{}在与jar的同级目录config目录下", fileName);
            return getInputStream(resource);
        }

        //这里是与JAR包同级目录下
        resource = resourceLoader.getResource("file:" + fileName);
        if (resource.exists()) {
            LOGGER.debug("{}在与JAR包同级目录下", fileName);
            return getInputStream(resource);
        }

        resource = resourceLoader.getResource("classpath:/" + fileName);
        if (resource.exists()) {
            LOGGER.debug("{}在jar里面的resources目录", fileName);
            return getInputStream(resource);
        }
        
        throw new RuntimeException("Resource Not Found:" + fileName);
    }

    private InputStream getInputStream(Resource resource) {
        try {
            return resource.getInputStream();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

读取springboot # resources下文件

        import org.springframework.util.ResourceUtils;

        File path = new File(ResourceUtils.getURL("classpath:").getPath());

        File file1 = new File(path.getAbsolutePath() +
                                    "/templates/testUpload.html");
        File file2 = new File(path.getAbsolutePath() +"/application.yaml");

读取当前应用下resource下的文件

    public static String getPath() {
        return TestFileUtil.class.getResource("/").getPath();
    }
            //读取resources目录下demo包内的xlsx文件
	        String fileName = "demo_has_error.xlsx";
	        String filePath = TestFileUtil.getPath() + "demo" 
	                                    + File.separator + fileName;
	        File file = new File(filePath);

创建可能不存在的文件

    @SneakyThrows
    private File createFile(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        if (!file.exists()) {
            createParentPath(file);
            file.createNewFile();
        }
        return file;
    }

    public void createParentPath(File file) {
        File parentFile = file.getParentFile();
        if (null != parentFile && !parentFile.exists()) {
            // 创建文件夹
            parentFile.mkdirs();
            // 递归创建父级目录
            createParentPath(parentFile);
        }
    }

本地读取资源文件

File file =new File("src/main/resources/properties/test.properties");

其它示例

此时我想读取 jar 包中根路径下的 HelloServiceEncryptFile.txt 文件,然后重新写入到根路径下的 com.study/service 路径下!

InputStream inputStream = 
         EncryptUtil.class.getResourceAsStream("/HelloServiceEncryptFile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();

// 获取类路径下的文件路径
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) {
   path = new File("");
}
log.info("path = {}", path.getAbsolutePath());
File upload = new File(path.getAbsolutePath(), "com/study/service");
if (!upload.exists()) {
    upload.mkdirs();
}
FileOutputStream fos = new FileOutputStream(upload.getAbsolutePath() 
        + File.separator + "hello.txt");
IoUtil.copy(inputStream, fos);
fos.close();
inputStream.close();

读取jar包内文件

使用Spring提供的ClassPathResource类能够读取到那个JAR包中的resources目录下的ffmpeg文件。比如下面的复制业务,通过ClassPathResource类就能读取到该JAR中的文件。

try {
   org.springframework.core.io.ClassPathResource resource =
               new ClassPathResource("ffmpeg/ffmpeg.exe");
 
   InputStream fis = resource.getInputStream();
 
 
   FileOutputStream outputStream = new FileOutputStream(  new File('目标文件路径') );
 
   org.apache.tomcat.util.http.fileupload.IOUtils.copy(fis, outputStream);
   //一定要关闭,不然复制的文件会报被占用错误
   outputStream.close();
 
} catch (Exception ex) {
    LOGGER.error("复制文件出错");
    throw new FfmpegException("复制文件出错");
}
LOGGER.info("文件复制结束");```
posted @ 2022-07-17 12:13  小大宇  阅读(50)  评论(0编辑  收藏  举报