2

I have a

URL url = new URL("/path/to/file.txt");

URLConnection urlConnection = url.openConnection();
urlConnection.setUseCaches(false);

and I read the contents of the file on Linux, cache is still used and I am not getting the actual contents if I change the contents.

Why is this not working? Shouldn't cache false get the latest?

Related: java.net.URL cache when reading from files

EDIT

    getBytes(urlConnection.getInputStream());    

    public static byte[] getBytes(InputStream inputStream) throws IOException {
            try ( InputStream is = inputStream; ByteArrayOutputStream bos = new ByteArrayOutputStream(BUFFER) ) {
                    byte[] buffer = new byte[BUFFER];

                    int length;
                    while ( (length = is.read(buffer)) != -1 ) {
                            bos.write(buffer, 0, length);
                    }

                    return bos.toByteArray();
            }
    }
Community
  • 1
  • 1
mjs
  • 21,431
  • 31
  • 118
  • 200

1 Answers1

2

One possible source of this problem that may be more prevalent on Linux is the fact that Linux has a "Buffer Cache".

Basically, to make disk I/O faster, writes may be buffered in memory, and not written to disk immediately. Depending on how the URLConnection implementation reads the file, it may be seeing the 'old' version that is still on disk instead of the 'new' version that is still in memory, but hasn't been flushed to the disk yet.

You don't say how you are changing the contents of the file, but if possible, either wait for the buffer cache to be flushed to disk, or force it to be flushed.

For more details, see http://www.tldp.org/LDP/sag/html/buffer-cache.html

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • But it doesnt matter if i wait more than 15 seconds. Maybe intellij isn't saving it? – mjs Aug 28 '15 at 12:18
  • Try doing the same thing using a different editor, something fairly low-level, from the command-line, like nano, or vi. – GreyBeardedGeek Aug 28 '15 at 12:20
  • Annoying, yes, but keep in mind that this is a development-time issue ony. The users of your app will not be running it via Android Studio. – GreyBeardedGeek Aug 28 '15 at 12:31