java 读取项目下文件和上传文件
读取项目下文件
1、硬盘绝对路径
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String path = "E:\\path\\1.txt";
File file = new File(path);
System.out.println(file.getAbsolutePath());//输出读取到的文件路径}2、相对路径读取
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String path = req.getServletContext().getRealPath("1.txt");
File file = new File(path);
System.out.println(file.getAbsolutePath());//输出读取到的文件路径}项目中写入文件
public void doLoad(HttpServletRequest request,@RequestParam(value = "file") MultipartFile file, HttpServletResponse response)throws ServletException, IOException {
// 获取文件名称(避免携带盘符,IE11/Edge浏览器是有盘符)
String fileName = file.getOriginalFilename();
String destFileName=req.getServletContext().getRealPath("")+"uploaded"+ File.separator+fileName;
File destFile = new File(destFileName);
// 创建上级文件夹
destFile.getParentFile().mkdirs();
// 文件流写入
file.transferTo(destFile);