SpringBoot向resources下写文件的两种方式
作者: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写文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
