Search code examples
javabufferedreaderfilewriterbufferedwriterinputstreamreader

How to create file only if there is data in BufferedReader?


I am receiving data from a stream and writing the result to a file

File resultFile = new File("/home/user/result.log");

BufferedWriter bw = new BufferedWriter(new FileWriter(resultFile));
BufferedReader stdInput2 = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s2 = null;
while ((s2 = stdInput2.readLine()) != null) {
    bw.write(s2+System.getProperty("line.separator"));
}
bw.close();

If there is no data, then an empty file will still be created.

Can you please tell me how can I make a check, if there is no data, then do not save the file? I don't need empty files.

Thank you.


Solution

  • First try to read a line, then create the file only if successful.

    File resultFile = new File("/home/user/result.log");
    
    BufferedWriter bw = null;
    BufferedReader stdInput2 = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String s2 = null;
    while ((s2 = stdInput2.readLine()) != null) {
        if (bw==null) {
            bw=new BufferedWriter(new FileWriter(resultFile));
        }
        bw.write(s2+System.getProperty("line.separator"));
    }
    if (bw!=null) {
        bw.close();
    }