java读取MultipartFile或者File格式文件内容

干货,拿去直接能运行的,亲测有效(测试用的txt文件)

// 读取MultipartFile文件内容  content就是文件内容
public String getJson(MultipartFile file) {
        String content = "";
        try {
           byte[] data = file.getBytes();
           content = new String(data, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    
// 读取File文件内容  content就是文件内容
    public  String getJson() {
        StringBuffer content = new StringBuffer("");
        try {
            File file = new File("此处是文件路径");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                content .append(line);
            }
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content .toString();
    }
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用MultipartFile类来读取上传的文件内容MultipartFile是Spring框架提供的一个接口,用于处理文件上传。 要读取MultipartFile文件内容,可以按照以下步骤进行操作: 1. 在Controller中,使用@RequestParam注解将MultipartFile对象作为参数接收文件上传请求。 2. 使用MultipartFile对象的getInputStream()方法获取文件的输入流。 3. 使用输入流进行文件内容读取。可以使用BufferedReader等类来读取文件内容。 下面是一个示例代码,演示了如何读取MultipartFile文件内容: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @RestController public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { InputStream inputStream = file.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder content = new StringBuilder(); while ((line = reader.readLine()) != null) { content.append(line); } reader.close(); inputStream.close(); return content.toString(); } catch (IOException e) { e.printStackTrace(); return "File upload failed."; } } } ``` 在上述示例中,通过调用file.getInputStream()方法获取文件的输入流。然后使用BufferedReader逐行读取文件内容,并将内容存储在StringBuilder中。最后返回文件内容的字符串表示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值