-1

I would like to read a text file after the contents have changed, but Java is caching the original contents of the file.

I have tried URLConnection.setUsesCaches(false), which didn't help. I also tried adding a changing dummy query string parameter, but again no help

Resource[] resources = applicationContext.getResources("classpath*:/" + file);

for (Resource resource:resources) {
    URL url = resource.getURL();
//   reconstruct the URL to remove any possible vestiges of the resource
    url = new URL(url.toString());
    URLConnection conn = url.openConnection();
    conn.setUseCaches(false); // Tried this first, but it did not work!
//    url = new URL(url.toString() + "?dummy=" + id); // tried this also, but it doesn't work at all
    InputStream inputStream = conn.getInputStream();

Is there any way to tell Java to re-read the new contents of a file?

Vinny Gray
  • 477
  • 5
  • 18
  • 2
    You read a file that resides on the CLASSPATH, as a resource. These things are meant to be constant/immutable, like a `*.class` file. – tquadrat May 24 '20 at 16:48
  • I don't think that is the reason - as you see, I am creating a new URL - it doesn't have any reference to the fact that it started as a classpath resource. It looks like it has something to do with the fact that it is a file: "/C:/dev/project/target/classes/my-file.html" – Vinny Gray May 24 '20 at 17:23
  • Are you sure that content of the file is changed? If you are using Spring, why do not use the Spring provided class for this kind of work? For example, check please this https://stackoverflow.com/a/36589635/5790398. – eg04lt3r May 24 '20 at 20:32
  • Yes, I am sure, I am manually changing it and saving it in my IDE. I had originally tried the Spring built-in class: Resource resource = new ClassPathResource("/application/context/references/user/user.xml"); But it didn't work, so I thought I would try to roll my own – Vinny Gray May 24 '20 at 23:07

1 Answers1

1

When you start your Spring on IDE, the classes are compiled to a specific output folder (target folder in your case), static resources are also copied to respective folder.

It mean to be constant and immutable when start the app, you need to manual copy your file to target folder (/target/classes/my-file.html) to have it updated (Spring only look for files in that target folder).

But let re-think your implementation, it would be wrong from begining when you tried to update a static resource file.

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
  • This is for diagnostic purposes, I am changing the file slowly, and redisplaying it, until it is perfect. Thanks! – Vinny Gray Jun 08 '20 at 23:30