0

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.

Thomazzz
  • 193
  • 2
  • 10
  • 1
    Personally, I'd probably just track if the bytes written, and delete the file if the number was zero. It is possible that [some answers from this question](https://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it) might be helpful (e.g., `PushbackInputStream`), but that seems like more effort IMO. – KevinO Apr 22 '21 at 19:16
  • KevinO 2, Thank you, I also thought about deleting files, but I was hoping for the possibility of an easy check for the presence of data in the stream before receiving it from it) – Thomazzz Apr 22 '21 at 19:19

1 Answers1

3

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();
}
Rocco
  • 1,098
  • 5
  • 11