-2
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";

//should just check if file is opened by someone else
try
{
    FileWriter fw = new FileWriter(pathSrc );
    fw.close();
}
catch (IOException e)
{
    System.out.println("File was already opened");
    return;
}

This code should just check if pdf file is already opened. Instead after that code pdf file is corrupted. and can no longer be opened. Why is that?

Marcela28
  • 17
  • 1
  • 5

1 Answers1

0

Note that FileWriter starts empty everytime you instantiate a FileWriter with the Filename only, and then starts writing the data to the beginning of the file.

There's a second constructor that takes a boolean append flag that starts at the end of the file, appending data to the current file's contents.

This means that your code erases the whole pdf file and then close()s it, saving an empty PDF file, with zero bytes.

This simple change will fix your issue:

String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";

//should just check if file is opened by someone else
try {
    FileWriter fw = new FileWriter(pathSrc, true);
    fw.close();
}
catch (IOException e) {
    System.out.println("File was already opened");
    return;
}
msmilkshake
  • 214
  • 1
  • 13
  • That wouldn't detect an already open file either on most platforms. – user207421 Aug 28 '20 at 00:08
  • Thanks. I should know better FileWriter API. But why do you think it would not work on all platforms. I think differently . Java is platform independant so it will work on all platforms in my opinion – Marcela28 Aug 28 '20 at 07:20