在笔记和资料库模块,用户可能想要下载笔记或者资料到本地,所以需要有一个下载文件到本地的操作。
代码如下:部分解析以注释体现
package project.ourcourseassistant.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class fileUtil {
public static String savaFileByNio(FileInputStream fis, String path) {
// 这个路径最后是在: 你的项目路径/FileSpace 也就是和src同级
// 判断父文件夹是否存在
File file = new File(path);
if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
file.getParentFile().mkdirs();
}
// 通过NIO保存文件到本地磁盘
try {
FileOutputStream fos = new FileOutputStream(path);
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
}