当前位置:首页 > java > 正文内容

java 读取项目下文件和上传文件

root5年前 (2021-11-10)java1746

读取项目下文件

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


扫描二维码推送至手机访问。

版权声明:本文由一叶知秋发布,如需转载请注明出处。

本文链接:https://zhiqiu.top/?id=172

分享给朋友:

相关文章

pom.xml文件的标签含义

<?xml version="1.0" encoding="UTF-8"?>声明xml的版本<project xmlns="http://maven.apache.org/...

java-Springboot的几个重要注解@controller、@service、 @repository、@component

1、@controller 控制器(注入服务)用于标注控制层,相当于struts中的action层2、@service 服务(注入dao)用于标注服务层,主要用来进行业务的逻辑处理3、@repository(实现dao访问)用于标注数据访问...

java 处理json 字符串

假设有一个实体类public class User{   private int id;   private String name;&...

java springboot @ApiModelProperty用法

@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 value–字段说明 name–重写属性名字 dataType–重写属性类型 required–是否...

java 发送http 请求

这里以post请求为例例1import cn.hutool.http.HttpRequest; public class HttpRequestUtil {    &...