Search code examples
javafile-ioproperties-file

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


What I already have:

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);

    }
}

This loads me the whole file1 and the whole file2 into prop and prop2. The whole file1 into prop is what I want but I only want to load a specific area of file2 into prop2. The area always starts with "[groups]" and always ends with "[". Both files are full of "team1 = user1, user2, user3" next line "team2 = user4, user 5, user 6" next line. But in file 2 there are also other things which I don't need. I only need the section which is written between the keyword "[groups]" and "[" Can anyone help me how to realize it?

Thanks in advance!


Solution

  • Another way of doing is to convert your file contents into StringBuilder and then subString that start with [groups] and end with [. Your code may look like this;

    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);
    

    You can use the below helper method to convert InputStream to StringBuilder for subString function.

    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;
    }