Skip to content

How to read file from a specific location and cache it just to avoid multiple calls

I have a simple requirement where I have to read a file from a specific location and upload it to a sharedPoint (a different location). Now this reading file process can be multiple times so to avoid multiple calls, I want to store the file into a cache and read it from there. Now I am not bothered on the contents of the file. Just have to read from the spefied location and upload. Adn my application is a Java application. Can anyone suggest best way to implement the above requirement.


As already mentioned there is usually no need to cache whole files. A primitive solution for a cache would be to store the binary data like that:

import java.nio.file.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FileCache {
    private final Map<Path, byte[]> cache = new ConcurrentHashMap<>();
    public byte[] read(Path file) throws IOException {
        byte[] data = cache.get(file);
        if (data == null) {
            data = Files.readAllBytes(file);
            cache.put(file, data);
        return data;