风的旅行

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;
		}
	}

  

posted on 2019-08-14 14:30  风的旅行  阅读(1266)  评论(0编辑  收藏  举报

导航