Java项目读取resources下的配置文件

资源文件准备

20190815194618.png

{
  "name": "Tom",
  "age": 19
}

读取方式

一、Java原生

使用 java 的 ClassLoader 来读取

public static void main(String[] args) throws IOException {
    String path = AreaCode.class.getClassLoader().getResource("student.json").getPath();
    // FileUtils 用的是 Apache common-io 包
    String string = FileUtils.readFileToString(new File(path), CharEncoding.UTF_8);
    System.out.println(string);
}

二、Spring

// 这种方式,当项目打成 jar 包放到服务器后就找不到文件了,打成jar包后必须以流的方式读取文件,看下面第三种方式。
public static void main(String[] args) {
    try {
        // org.springframework.core.io 包
        Resource resource = new ClassPathResource("student.json");
        File file = resource.getFile();
        // FileUtils 用的是 Apache common-io 包
        String string = FileUtils.readFileToString(file, CharEncoding.UTF_8);
        System.out.println(string);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

三、以流的方式读取

tips: jar包的情况下linux下不能得到resource下的文件的路径, 打成jar包后必须以流的方式读取文件

ClassLoader 获取文件流

public static void main(String[] args) throws IOException {
    // 这种方式也是使用 java 的 ClassLoader 来读取
    InputStream inputStream = AreaCode.class.getClassLoader().getResourceAsStream("student.json");
    StringBuilder out = new StringBuilder();
    byte[] b = new byte[4096];
    // 读取流
    for (int n; (n = inputStream.read(b)) != -1; ) {
        out.append(new String(b, 0, n));
    }
    System.out.println(out.toString());
}

Spring 获取文件流

与上面 Spring 方式类似,只是把文件转换成输入流了

public static void main(String[] args) throws IOException {
    Resource resource = new ClassPathResource("student.json");
    InputStream inputStream = resource.getInputStream();
    StringBuilder out = new StringBuilder();
    byte[] b = new byte[4096];
    // 读取流
    for (int n; (n = inputStream.read(b)) != -1; ) {
        out.append(new String(b, 0, n));
    }
    System.out.println(out.toString());
}

上面的输出结果均为:

20190815194812.png

Properties文件

Properties 文件读取不必使用上面的方法,有更简单的方法,具体看我另外一篇博客:
Java 读取 Properties 文件

感谢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章