需求:删除文件
File delFile = new File(diskFilePath);
if(diskFilePath != "" && diskFilePath != null && delFile.isFile() && delFile.exists() {
delFile.delete();
}
需求:将文件转移到另一个文件位置
使用Commons IO复制
FileUtils.copyFile(sourceFile,destFile);
使用Java7的Files类复制
Files.copy(sourceFile.toPath(),destFile.toPath());
//PS
new File(endDirection+ File.separator+ startFile.getName());
需要:将文件的bytes存放到磁盘中
/**
* @Description: 将文件存放到磁盘中
* @Param: [filebytes, filepath]
* @return: void
* @about=>yangjianzhi-version1.0-2019/7/26
*/
public static boolean bytesTransDisk(byte[] filebytes, String filepath) {
boolean retMsg = true;
System.out.println("开始将数据库pdf文件存入:" + filepath);
try {
//1. 实例化二进制缓存输入流
BufferedInputStream fbyteInput = new BufferedInputStream(new ByteArrayInputStream(filebytes));
//2. 创建新文件 示例化文件输出流 => 缓存输出流
File nfile = new File(filepath);
if (!nfile.exists()) {
System.out.println("文件夹不存在,创建;filepath:" + filepath);
boolean isCreated = nfile.mkdirs();
if (!isCreated) {
System.out.println("创建文件夹失败!");
}
}
BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(nfile));
//3. 1二进制缓存输入流 =流入=> 2文件的缓存输出流,从而将二进制数据保存到磁盘中
byte[] buffer = new byte[1024];
int length = fbyteInput.read(buffer);
while (length != -1) {
fileOut.write(buffer, 0, length);
length = fbyteInput.read(buffer);
}
fileOut.flush();
System.out.println("成功!");
} catch (Exception e) {
retMsg = false;
System.out.println("输出文件流时抛异常,filepath=" + filepath);
}
System.out.println("结束!");
return retMsg;
}
需求:文件不存在则创建
/**
* 创建目录
*
* @param path
*/
public static void CreatFileDir(String path) {
try {
File file = new File(path);
if(file.getParentFile().isDirectory()){//判断上级目录是否是目录
if(!file.exists()){ //如果文件目录不存在
file.mkdirs(); //创建文件目录
}
}else{
throw new Exception("传入目录非标准目录名");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void CreatFile(String path) {
try {
File file = new File(path);
if(file.getParentFile().isDirectory()){//判断上级目录是否是目录
if(!file.exists()){ //如果文件不存在
file.createNewFile(); //创建文件
}
}else{
throw new Exception("传入目录非标准文件名");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//创建新文件,将源文件转移到新文件;判断目录是否存在不存在创建
newFile = new File(uploadPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}