'How to properly read and write files in Gradle resources?

Java Gradle project File saving in build/resources, but reading from src/resources Does anyone know how to save and read from the same directory? below is my code for writing:

     File file = new File((this.getClass().getClassLoader().getResource("test.txt")).toURI());

     FileWriter fw = new FileWriter(file, false);
     BufferedWriter bw = new BufferedWriter(fw);

     PrintWriter pw = new PrintWriter(bw);

     pw.println("test");
     pw.close();

below is my code for reading:

     BufferedReader br = new BufferedReader(new FileReader(new File((this.getClass().getClassLoader().getResource("test.txt")).toURI())));
     String amount = br.readLine();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source