Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
    private static ConcurrentHashMap<String, ReentrantReadWriteLock> fileLocks = new ConcurrentHashMap();

    public static byte[] readContentBytesFromFile(File fileForRead) {
        if (fileForRead == null) {
            return null;
        } else if (fileForRead.exists() && fileForRead.isFile()) {
            ReentrantReadWriteLock.ReadLock readLock = getLock(fileForRead.getAbsolutePath()).readLock();
            readLock.lock();
            Object data = null;
            BufferedInputStream input = null;

            try {
                byte[] data1 = new byte[(int) fileForRead.length()];
                int e = 0;
                input = new BufferedInputStream(new FileInputStream(fileForRead), 8192);

                while (e < data1.length) {
                    int bytesRemaining = data1.length - e;
                    int bytesRead = input.read(data1, e, bytesRemaining);
                    if (bytesRead > 0) {
                        e += bytesRead;
                    }
                }

                byte[] bytesRemaining1 = data1;
                return bytesRemaining1;
            } catch (IOException var10) {
            } finally {
                closeQuietly(input);
                readLock.unlock();
            }

            return null;
        } else {
            return null;
        }
    }

    private static ReentrantReadWriteLock getLock(String path) {
        ReentrantReadWriteLock lock = (ReentrantReadWriteLock) fileLocks.get(path);
        if (lock == null) {
            lock = new ReentrantReadWriteLock();
            ReentrantReadWriteLock oldLock = (ReentrantReadWriteLock) fileLocks.putIfAbsent(path, lock);
            if (oldLock != null) {
                lock = oldLock;
            }
        }

        return lock;
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException var2) {
            //log.d(var2.toString());
        }

    }
}