SpringBoot向resources下写文件的两种方式
更新时间:2023年08月25日 09:39:35 作者:zhou_zhao_xu
这篇文章给大家分享了两种SpringBoot向resources下写文件的方式,每种方式都有详细的代码示例,对我们的学习或工作有一定的帮助,需要的朋友可以参考下
方式一:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriterFileUtils {
private static final String prefix = "classpath:";
public static void writeFile(String directory, String fileName, String content){
directory = prefix + directory;
try {
File dir = new File(directory);
if (!dir.exists()){
dir.mkdir();
}
String filePath = directory + fileName;
File file = new File(filePath);
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(filePath);
fw.write(content);
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}方式二:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
/**
* @author zzx
* @version : WriterFileUtils.java, v 0.1 2023年08月22日 11:24 zzx Exp $
*/
public class WriterFileUtils {
public static final WriterFileUtils INSTANCE = new WriterFileUtils();
@Autowired
private ResourceLoader resourceLoader;
private static final String prefix = "classpath:";
public void writeFile(String directory, String fileName, String content){
try {
directory = prefix + directory;
Resource dirResource = resourceLoader.getResource(directory);
File dir = dirResource.getFile();
if (!dir.exists()){
dir.mkdir();
}
String filePath = directory + fileName;
Resource fileResource = resourceLoader.getResource(filePath);
File file = fileResource.getFile();
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(filePath);
fw.write(content);
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}到此这篇关于SpringBoot向resources下写文件的两种方式的文章就介绍到这了,更多相关SpringBoot向resources写文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
redis redisson 集合的使用案例(RList、Rset、RMap)
这篇文章主要介绍了redis redisson 集合的使用案例(RList、Rset、RMap),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
spring boot加入拦截器Interceptor过程解析
这篇文章主要介绍了spring boot加入拦截器Interceptor过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-10-10
解决mapper自动装配识别不了,Could not autowire.No beans&
文章介绍了在使用MyBatisX插件和MybatisPlus自动生成代码后,如何解决Spring Boot项目中自动注入`UserMapper`时报错的问题,主要方法包括在主配置类或启动类上添加`@MapperScan`注解,指定Mapper文件夹所在的包路径,以及在Mapper类上添加`@Repository`注解2024-11-11


最新评论