是否有一种方法将资源中的文本文件读入字符串?

我想这是一个普遍的需求,但我在谷歌上找不到任何实用工具。


当前回答

我创建了这样一个NO-dependency静态方法:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}

其他回答

我创建了这样一个NO-dependency静态方法:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}

纯粹而简单,jar友好的Java 8+解决方案

如果你使用的是Java 8或更高版本,下面这个简单的方法就可以了:

/**
 * Reads given resource file as a string.
 *
 * @param fileName path to the resource file
 * @return the file's contents
 * @throws IOException if read fails for any reason
 */
static String getResourceFileAsString(String fileName) throws IOException {
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try (InputStream is = classLoader.getResourceAsStream(fileName)) {
        if (is == null) return null;
        try (InputStreamReader isr = new InputStreamReader(is);
             BufferedReader reader = new BufferedReader(isr)) {
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        }
    }
}

它还可以处理jar文件中的资源。

关于文本编码:如果您没有指定,InputStreamReader将使用默认的系统字符集。你可能想要自己指定它来避免解码问题,像这样:

new InputStreamReader(isr, StandardCharsets.UTF_8);

避免不必要的依赖

总是不喜欢依赖于大而胖的库。除非您已经将Guava或Apache Commons IO用于其他任务,否则将这些库添加到项目中只是为了能够从文件中读取,这似乎有点过分。

下面是我的方法

public String getFileContent(String fileName) {
    String filePath = "myFolder/" + fileName+ ".json";
    try(InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
        return IOUtils.toString(stream, "UTF-8");
    } catch (IOException e) {
        // Please print your Exception
    }
}

Guava也有Files.readLines()如果你想要一个List<String>一行一行的返回值:

List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);

请参考这里比较3种方法(BufferedReader vs. Guava's Files vs. Guava's Resources)从文本文件中获取字符串。

下面的代码对我有用:

compile group: 'commons-io', name: 'commons-io', version: '2.6'

@Value("classpath:mockResponse.json")
private Resource mockResponse;

String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");