java删除上传_Java中上传文件到代码中和删除代码中的文件

1.上传文件到指定的项目地址中

@ResponseBody // 返回json数据

@ApiOperation(value = "图片上传生成地址")

@RequestMapping(value = "/testUploadimg", method = RequestMethod.POST)

public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

String path = "";

String contentType = file.getContentType();

String fileName = file.getOriginalFilename();

// 自动获取项目的根路径

String filePath = request.getSession().getServletContext().getRealPath("/") + "img/";//这块可以填写相应的位置

// String filePath = "";

if (file.isEmpty()) {

return "文件为空!";

}

try {

// 把文件保存到项目中

path = uploadFile(file.getBytes(), filePath, fileName);

} catch (Exception e) {

// TODO: handle exception

}

// 返回json

return path;

}

public String uploadFile(byte[] file, String filePath, String fileName) throws Exception {

String path = "";

File targetFile = new File(filePath);

if (!targetFile.exists()) {

targetFile.mkdirs();

}

FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);

path = filePath + "/" + fileName;

out.write(file);

out.flush();

out.close();

return path;

}

2.在项目中删除指定文件和文件夹

public boolean fileTest(String path) {

// 删除文件

String strVectorFile = path;

boolean bo = deleteFile(strVectorFile);

// 删除文件夹

String strVectorDir = "D:\\test2";

deleteDirectory(strVectorDir);

return bo;

}

public static boolean deleteFile(String fileName) {

File file = new File(fileName);

if (file.isFile() && file.exists()) {

Boolean succeedDelete = file.delete();

if (succeedDelete) {

System.out.println("删除单个文件" + fileName + "成功!");

return true;

} else {

System.out.println("删除单个文件" + fileName + "失败!");

return true;

}

} else {

System.out.println("删除单个文件" + fileName + "失败!");

return false;

}

}

public static boolean deleteDirectory(String dir) {

// 如果dir不以文件分隔符结尾,自动添加文件分隔符

if (!dir.endsWith(File.separator)) {

dir = dir + File.separator;

}

File dirFile = new File(dir);

// 如果dir对应的文件不存在,或者不是一个目录,则退出

if (!dirFile.exists() || !dirFile.isDirectory()) {

System.out.println("删除目录失败" + dir + "目录不存在!");

return false;

}

boolean flag = true;

// 删除文件夹下的所有文件(包括子目录)

File[] files = dirFile.listFiles();

for (int i = 0; i < files.length; i++) {

// 删除子文件

if (files[i].isFile()) {

flag = deleteFile(files[i].getAbsolutePath());

if (!flag) {

break;

}

}

// 删除子目录

else {

flag = deleteDirectory(files[i].getAbsolutePath());

if (!flag) {

break;

}

}

}

if (!flag) {

System.out.println("删除目录失败");

return false;

}

// 删除当前目录

if (dirFile.delete()) {

System.out.println("删除目录" + dir + "成功!");

return true;

} else {

System.out.println("删除目录" + dir + "失败!");

return false;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值