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.Closeable;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

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

    public static boolean saveContentToFile(String content, File fileForSave) {
        try {
            return saveContentToFile(content.getBytes("utf-8"), fileForSave);
        } catch (UnsupportedEncodingException var3) {
            //log.d(var3.toString());
            return false;
        }
    }

    public static boolean saveContentToFile(byte[] content, File fileForSave) {
        ReentrantReadWriteLock.WriteLock writeLock = getLock(fileForSave.getAbsolutePath()).writeLock();
        boolean succeed = true;
        FileOutputStream out = null;
        if (writeLock.tryLock()) {
            try {
                out = new FileOutputStream(fileForSave, false);
                out.write(content);
            } catch (Exception var9) {
                //log.d(var9.toString());
                succeed = false;
            } finally {
                if (out != null) {
                    closeQuietly(out);
                }

                writeLock.unlock();
            }
        }

        return succeed;
    }

    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());
        }

    }
}