Is there a way to set a breakpoint whenever a file is created in Java, using IntelliJ Idea?

67 Views Asked by At

After doing a complex build of a multi-module project in IntelliJ, somehow several 0-length files get generated or created somehow. I want to debug the build process and set a conditional breakpoint whenever a file is created with a specific name. Is there a way to do that?

I tried setting a breakpoint in the File() constructors, but apparently these zero-length files get created without creating a File class instance, because my conditional breakpoint is never hit. I also tried a breakpoint in File#createNewFile(), but it was never hit.

I even tried creating directories with the names of the 0-length files, so that attempting to create them as files would fail. After the build, those remained directories, and no exceptions or errors occurred during the build.

This seems like it ought to be possible. There is too much IntelliJ code and Gradle code and my own application's code to look through and guess where these zero-length files are being created.

2

There are 2 best solutions below

1
leaf_yakitori On
  • I think maybe an external static util class create the file, so even you set a breakpoint in File but never hit it.

  • Some debug advices in this situation:

a file is created with a specific name

  1. since the file name is a specific name, hit shift twice to search this name, you may find it.
  2. or the name was constructed by a certain way, such as 20240125.txt, then search something like Date+".txt"
  3. check the created time of files, think which part of code may run in that time.

I tried setting a breakpoint

  1. since you can set breakpoint, you can debug the application module by module, check which module/class/method called then the file appears.
  2. add a condition breakpoint in a Interceptor, check the folder size or file name all the time, if the new file appears then hit it.
2
farwind On

3 methods to create empty file (length of file is 0) in Java, try add breakpoints to them:

  1. File.createNewFile()

  2. FileOutputStream.write(byte[] b)

    String fileData = "";
    FileOutputStream fos = new FileOutputStream("file.txt");
    fos.write(fileData.getBytes());
    fos.flush();
    fos.close();
  1. java.nio.Files.write()
    String fileData = "";
    Files.write(Paths.get("file.txt"), fileData.getBytes());