All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.arp.javautil.io.UniqueDirectoryCreator Maven / Gradle / Ivy

Go to download

JavaUtil is a utility library to speed the development of Java software. We developed it over multiple years during our internal development efforts, and it has reached a point of stability where we have decided to make it available to the outside world. The JavaUtil package aims to fill in the gaps of the Apache Commons and similar utility libraries out there. Features include convenience classes for string, collections, arrays, dates, iterators, colors, logging, unit testing, a little bit of basic statistics, database queries, caching and more.

There is a newer version: 4.5
Show newest version
/*
 * #%L
 * JavaUtil
 * %%
 * Copyright (C) 2012 - 2013 Emory University
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
package org.arp.javautil.io;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * Creates directories with a unique name.
 *
 * @author Andrew Post
 */
public class UniqueDirectoryCreator {

    protected static final Object tmpDirectoryLock = new Object();
    private int counter = -1;

    public File create(String prefix, String suffix, File directory)
            throws IOException {
        if (prefix == null) {
            throw new NullPointerException();
        }
        if (prefix.length() < 3) {
            throw new IllegalArgumentException("Prefix string too short");
        }
        if (directory == null) {
            throw new IllegalArgumentException("directory cannot be null");
        }
        return doGenerateFile(prefix, suffix, directory);
    }

    protected File doGenerateFile(String prefix, String suffix, File directory) throws IOException {
        String s = (suffix == null) ? "" : suffix;
        synchronized (tmpDirectoryLock) {
            File f;
            Random random = new Random();
            do {
                if (counter == -1) {
                    counter = random.nextInt() & 0xffff;
                }
                counter++;
                f = new File(directory, prefix + Integer.toString(counter) + s);
            } while (!f.mkdir());

            return f;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy