如何将文件的特定区域加载到 属性 - Java

How can I load a specific area of a file into a Property - Java

我已有的:

public static void main(String[] args) throws Exception {

    Properties prop = new Properties();
    Properties prop2 = new Properties();

    InputStream is = new FileInputStream("file1");
    InputStream is2 = new FileInputStream("file2");

    prop.load(is);
    prop2.load(is2);

    }
}

这会将整个 file1 和整个 file2 加载到 prop 和 prop2 中。 整个 file1 到 prop 是我想要的,但我只想将 file2 的特定区域加载到 prop2。该区域始终以“[groups]”开头,始终以“[”结尾。 两个文件都充满 "team1 = user1, user2, user3" 下一行 "team2 = user4, user 5, user 6" 下一行。但是在文件 2 中还有其他一些我不需要的东西。我只需要写在关键字“[groups]”和“[”之间的部分 谁能帮我实现一下?

提前致谢!

Properties API 没有提供这样的功能。
作为解决方法,流式传输符合您条件的属性和过滤器条目:

prop2 = prop2.entrySet()
                 .stream()
                 .filter(e -> {
                     String key = e.getKey()
                                   .toString();
                     return key.startsWith("[groups]") && key.endsWith("]");
                 })
                 .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (v1, v2) -> {
                     throw new RuntimeException("dup key");
                 }, Properties::new));

但是如果你的文件很大,这应该没问题。

我在 mergeFunction 中指定在键具有重复值时抛出 RuntimeException(这可能是一项理想的检查),但如果有意义,您可以选择其他行为。

另一种方法是将您的文件内容转换为 StringBuilder 然后 subString[groups] 开头并以 [ 结尾。您的代码可能如下所示;

Properties prop = new Properties();
Properties prop2 = new Properties();

InputStream is = new FileInputStream("file1");      
InputStream is2 = new FileInputStream("file2");

StringBuilder fileData= convertToString(is2);
int start = fileData.indexOf("[groups]");
int end = fileData.indexOf("[", start + 8) + 1;

InputStream file2Section = new ByteArrayInputStream(fileData.substring(start, end).toString().getBytes());

prop.load(is);
prop2.load(file2Section);

您可以使用以下辅助方法将 InputStream 转换为 StringBuilder 以实现 subString 功能。

private StringBuilder convertToString(InputStream inputStream) throws IOException {
    StringBuilder textBuilder = new StringBuilder();
    try (Reader reader = new BufferedReader(
            new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
        int c = 0;
        while ((c = reader.read()) != -1) {
            textBuilder.append((char) c);
        }
    }
    return textBuilder;
}