Search code examples
javainputstreambufferedreaderwriter

Combine Multiple InputStreams


My question may be something really basic, but I am not able to find a working solution.

In my code I have three new InputStreams.

InputStream fstream = WasuTimeTool.class.getResourceAsStream("/resources/dbConParam.txt");
BufferedReader dbParamReader = new BufferedReader(new InputStreamReader(fstream));
String dbParamLine;

Simple as that. Everyone is the same beside the InputStreamString and the variables. They are build like that:

Stream One {

}

Stream Two {
    Stream Three {
    }
}

When I build a global Streams I got some problems with the use of the variable and the collision from the second and third stream. Is there a solutions to get one single Stream and make new Instances or should they stay as three different streams?


Solution

  • InputStream fstream = WasuTimeTool.class.getResourceAsStream("/resources/dbConParam.txt");
    BufferedReader dbParamReader = new BufferedReader(new InputStreamReader(fstream));
    String dbParamLine;
    

    Is more like

    Stream one{
       Stream two{
           Stream three{
           }
       }
    }
    

    This is correct and ok.

    Remember: Closing of the BufferedReader (aka Stream one) will close the InputStreamReader and the InputStream too!

    Sometimes the Streams internally have a small cache. To respect that behaviour you shall use the Stream with the most abstract level, BufferedReader in your example so faar.

    Example

    If you have this file:

    Hello
    Friend
    

    And you read Hello\nFri using the InputStream, then if you use readLine from BufferedReader you will become end. This is bad because it is not the whole line we accept from the method readLine!

    Solution

    You should do this:

    BufferedReader dbParamReader = new BufferedReader(new InputStreamReader(WasuTimeTool.class.getResourceAsStream("/resources/dbConParam.txt")));
    String dbParamLine;
    

    So noone can be inveigled to use the InputStream directly.