xqqlyx

Spring IO工具类及其用法

Spring IO 工具类

  1. FileCopyUtils
    用于文件和流之间的复制操作,提供了多种重载方法。
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

// 复制文件
File source = new File("source.txt");
File dest = new File("dest.txt");
FileCopyUtils.copy(source, dest);

// 从输入流复制到输出流
try (FileInputStream in = new FileInputStream(source);
     FileOutputStream out = new FileOutputStream(dest)) {
    FileCopyUtils.copy(in, out);
}

// 读取文件内容为字符串
String content = FileCopyUtils.copyToString(
    new FileReader(source, StandardCharsets.UTF_8)
);
  1. StreamUtils
    提供对流的各种操作,如复制、转换为字节数组等。
import org.springframework.util.StreamUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;

// 从流中读取字节数组
ByteArrayInputStream in = new ByteArrayInputStream("test".getBytes());
byte[] bytes = StreamUtils.copyToByteArray(in);

// 流之间的复制
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamUtils.copy(in, out);

// 流转换为字符串
String str = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
  1. Resource 接口及实现类
    统一资源访问接口,支持多种资源类型(文件、classpath资源、URL等)。
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

// 访问classpath下的资源
Resource classPathResource = new ClassPathResource("config.properties");

// 访问文件系统资源
Resource fileResource = new FileSystemResource("data/file.txt");

// 访问URL资源
Resource urlResource = new UrlResource("https://example.com/data.xml");

// 读取资源内容
try (InputStream is = resource.getInputStream()) {
    String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
}
  1. FileSystemUtils
    提供文件系统相关的工具方法,如递归删除目录。
import org.springframework.util.FileSystemUtils;
import java.io.File;

// 递归删除目录
File directory = new File("tempDir");
boolean deleted = FileSystemUtils.deleteRecursively(directory);
  1. ResourceUtils
    用于资源定位的工具类,帮助获取资源的File对象。
import org.springframework.util.ResourceUtils;
import java.io.File;

// 获取classpath下的资源文件
File file = ResourceUtils.getFile("classpath:data.json");

// 获取URL资源
File urlFile = ResourceUtils.getFile("https://example.com/file.txt");

posted on 2025-09-23 15:19  烫烫烫烫热  阅读(7)  评论(0)    收藏  举报