Java读取静态文本文件的三种方式

1. 读取文件路径及文件内容

配置在resource目录下

在这里插入图片描述

2. 获取方式
方式一

第一种方式我出现了一个问题, 本地是可以正常读取文件的,但是推上去部署成功后就不可以正常读取, 后来采用第二种方式, 如果也存在的话,也可以尝试一下

    public List<String> getTextMethod1() {
        // 读取配置文件
        List<String> list = new ArrayList<>();
        // 从AppClassLoader类加载器获取资源
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/area.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (Exception e) {
            throw new RuntimeException("获取异常!");
        } finally {
            try {
                reader.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
方式二
    public List<String> getTextMethod2() {
        List<String> list;
        try {
            Resource resource = new ClassPathResource("static/area.txt");
            Path myAllowWordsPath = Paths.get(resource.getFile().getPath());
            list = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);
        } catch (IOException ioException) {
            throw new RuntimeException("获取异常!");
        }
        return list;
    }
方式三

经测试第三种方法是需要在文件前加 classpath:

    @Autowired
    private ResourceLoader resourceLoader;

    // 方式三
    public List<String> getTextMethod3() {
        Resource resource = resourceLoader.getResource("classpath:static/area.txt");
        List<String> list = new ArrayList<>();
        String s;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
            while ((s = reader.readLine()) != null) {
                list.add(s);
            }
        } catch (IOException e) {
            throw new RuntimeException("获取异常!");
        }
        return list;
    }
三种方法汇总
import com.saas.common.core.web.domain.AjaxResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : Cookie
 * date : 2023/12/18
 */
@RestController("/textArea")
@Api(tags = "测试获取静态文件")
public class TextAreaController {

    @GetMapping("/getText1")
    public AjaxResult getText1() {
        return AjaxResult.success(getTextMethod1());
    }

    @GetMapping("/getText2")
    public AjaxResult getText2() {
        return AjaxResult.success(getTextMethod2());
    }

    @GetMapping("/getText3")
    public AjaxResult getText3() {
        return AjaxResult.success(getTextMethod3());
    }

    // 方式一
    public List<String> getTextMethod1() {
        // 读取配置文件
        List<String> list = new ArrayList<>();
        // 从AppClassLoader获取资源
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/area.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (Exception e) {
            throw new RuntimeException("获取异常!");
        } finally {
            try {
                reader.close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    // 方式二
    public List<String> getTextMethod2() {
        List<String> list;
        try {
            Resource resource = new ClassPathResource("static/area.txt");
            Path myAllowWordsPath = Paths.get(resource.getFile().getPath());
            list = Files.readAllLines(myAllowWordsPath, StandardCharsets.UTF_8);
        } catch (IOException ioException) {
            throw new RuntimeException("获取异常!");
        }
        return list;
    }

    @Autowired
    private ResourceLoader resourceLoader;

    // 方式三
    public List<String> getTextMethod3() {
        Resource resource = resourceLoader.getResource("classpath:static/area.txt");
        List<String> list = new ArrayList<>();
        String s;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
            while ((s = reader.readLine()) != null) {
                list.add(s);
            }
        } catch (IOException e) {
            throw new RuntimeException("获取异常!");
        }
        return list;
    }
}

3. 结果

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Cloud中,我们可以使用Spring Framework提供的ResourceLoader接口来读取静态文件。 首先,我们需要在Spring Boot应用的classpath下创建一个名为"resources"的文件夹,将静态文件(如文本文件、配置文件等)放置在其中。 然后,在我们的Spring Boot应用中,我们可以通过注入ResourceLoader接口来实现对静态文件读取。例如,在一个Controller类中,我们可以如下定义一个方法来读取静态文件: ```java @Autowired private ResourceLoader resourceLoader; @GetMapping("/readFile") public String readFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:static/myFile.txt"); File file = resource.getFile(); // 执行文件读取操作,例如: try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } } ``` 在上述代码中,"classpath:static/myFile.txt"指定了要读取静态文件的路径。getResource()方法将该路径解析为Resource对象,然后我们可以通过getFile()方法获取该文件的File对象。接下来,我们可以利用File对象执行文件读取操作,读取文件的内容并返回。 需要注意的是,如果静态文件位于jar包内部,则无法通过getFile()方法获取文件的File对象。此时,我们可以使用其他方法,如使用InputStream进行读取,如下所示: ```java @Autowired private ResourceLoader resourceLoader; @GetMapping("/readFile") public String readFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:static/myFile.txt"); InputStream inputStream = resource.getInputStream(); // 执行文件读取操作,例如: try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } } ``` 以上示例演示了如何读取静态文件,无论文件是放置在classpath下还是在jar包内部。使用ResourceLoader接口,我们可以很方便地读取静态文件并执行相应的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yfs1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值