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

Time:09-23

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.

CodePudding user response:

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.io.IOException;
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;
    }
}

CodePudding user response:

It depends on the situation, but generally speaking it is something the operation system should do. Operation system knows better, which files are "good" enough to be cached.

Caching programmatically can make sense only in case of very small file. In this case the requesting of the file system is more expensive, than the file transfer.

The simplest ways is to read the content into a ByteArrayInputStream. It stores the content of the file as a byte array. There are lot of different ways to do it. See this topic:

File to byte[] in Java

  •  Tags:  
  • java
  • Related