Example usage for java.io File mkdir

List of usage examples for java.io File mkdir

Introduction

In this page you can find the example usage for java.io File mkdir.

Prototype

public boolean mkdir() 

Source Link

Document

Creates the directory named by this abstract pathname.

Usage

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void copyAllContent(final String source, final String target, final boolean ignoreHidden)
        throws Exception {
    File sourceFile = new File(source);
    File targetFile = new File(target);
    if (!targetFile.exists()) {
        targetFile.mkdirs();//  ww  w. ja  v  a  2  s  .  c o m
    }
    if (sourceFile.exists() && sourceFile.canRead() && sourceFile.isDirectory() && targetFile.exists()
            && targetFile.canWrite() && targetFile.isDirectory()) {
        List<File> copyList = new ArrayList<File>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File file, String name) {
                return !ignoreHidden || !name.startsWith(".");
            }

        };
        File files[] = sourceFile.listFiles(filter);
        if (files.length > 0) {
            copyList.addAll(Arrays.asList(files));
        }
        for (int index = 0; index < copyList.size(); index++) {
            File aFile = copyList.get(index);
            String relativePath = aFile.getAbsoluteFile().getAbsolutePath()
                    .replaceFirst(sourceFile.getAbsoluteFile().getAbsolutePath(), "");
            if (aFile.isDirectory()) {
                File newDir = new File(target, relativePath);
                if (newDir.mkdir()) {
                    newDir.setExecutable(aFile.canExecute(), false);
                    newDir.setReadable(aFile.canRead(), false);
                    newDir.setWritable(aFile.canWrite(), false);
                    newDir.setLastModified(aFile.lastModified());
                    files = aFile.listFiles(filter);
                    if (files.length > 0) {
                        copyList.addAll(index + 1, Arrays.asList(files));
                    }
                } else {
                    log.warn("Failed to create new subdirectory \"{}\" in the target path \"{}\".",
                            relativePath, target);
                }
            } else {
                File newFile = new File(target, relativePath);
                if (newFile.createNewFile()) {
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    try {
                        inStream = new FileInputStream(aFile);
                        outStream = new FileOutputStream(newFile);
                        streamCopy(inStream, outStream);
                    } finally {
                        if (inStream != null) {
                            try {
                                inStream.close();
                            } catch (Exception e) {
                            }
                        }
                        if (outStream != null) {
                            try {
                                outStream.flush();
                            } catch (Exception e) {
                            }
                            try {
                                outStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                    newFile.setExecutable(aFile.canExecute(), false);
                    newFile.setReadable(aFile.canRead(), false);
                    newFile.setWritable(aFile.canWrite(), false);
                    newFile.setLastModified(aFile.lastModified());
                }
            }
        }
    }
}

From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java

public static String saveMultipartFileByTimePath(MultipartFile file, String uploadPath) {
    String uploadedFilePath = null;
    try {/* w  ww. ja  va  2  s . c o m*/
        String oldFileName = file.getOriginalFilename();
        String extension = DocumentProcessorUtil.getFileExtension(oldFileName);
        oldFileName = DocumentProcessorUtil.getFileNameWithoutExtension(oldFileName);
        //In the future the new file name will also has the user name
        String time = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        String newFileName = oldFileName + "." + extension;

        if (null != uploadPath) {
            File uploadFolder = new File(uploadPath);
            if (!uploadFolder.exists()) {
                uploadFolder.mkdir();
            }
            File uploadTimeFolder = new File(uploadPath + File.separator + time);
            if (!uploadTimeFolder.exists()) {
                uploadTimeFolder.mkdir();
            }
        }
        uploadedFilePath = uploadPath + File.separator + time + File.separator + newFileName;
        File uploadedFile = new File(uploadedFilePath);
        file.transferTo(uploadedFile);
    } catch (Exception ex) {
        Logger.getLogger(DocumentProcessorUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return uploadedFilePath;
}

From source file:com.hmiard.blackwater.projects.Builder.java

/**
 * Simple directory creation ;/*from w  ww .jav  a 2  s .co  m*/
 * won't erase the existing directory if it already exists.
 *
 * @param url String
 */
public static void buildFolder(String url) {

    File folder = new File(url);
    if (folder.exists() && folder.isDirectory()) {
        Start.displayWarning("The directory " + url + " already exists !");
        return;
    }
    if (!folder.mkdir())
        System.out.println("Cannot create the following folder : " + url);
}

From source file:core.AnnotationTask.java

public static void copyFolder(File src, File dest) throws IOException {

    if (src.isDirectory()) {

        //if directory not exists, create it
        if (!dest.exists()) {
            dest.mkdir();
            System.out.println("Directory copied from " + src + "  to " + dest);
        }//w  ww.j  av a  2s  .c  om

        //list all the directory contents
        String files[] = src.list();

        for (String file : files) {
            //construct the src and dest file structure
            File srcFile = new File(src, file);
            File destFile = new File(dest, file);
            //recursive copy
            copyFolder(srcFile, destFile);
        }

    } else {
        //if file, then copy it
        //Use bytes stream to support all file types
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes 
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        in.close();
        out.close();
        //System.out.println("File copied from " + src + " to " + dest);
    }
}

From source file:edu.iu.daal_kmeans.regroupallgather.KMUtil.java

/**
 * Generate data and upload to the data dir.
 * /*from w  w  w .  j  a  v  a 2 s.  co m*/
 * @param numOfDataPoints
 * @param vectorSize
 * @param numPointFiles
 * @param localInputDir
 * @param fs
 * @param dataDir
 * @throws IOException
 * @throws InterruptedException
 * @throws ExecutionException
 */
static void generatePoints(int numOfDataPoints, int vectorSize, int numPointFiles, String localInputDir,
        FileSystem fs, Path dataDir) throws IOException, InterruptedException, ExecutionException {
    int pointsPerFile = numOfDataPoints / numPointFiles;
    System.out.println("Writing " + pointsPerFile + " vectors to a file");
    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();
    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }
    if (pointsPerFile == 0) {
        throw new IOException("No point to write.");
    }
    // Create random data points
    int poolSize = Runtime.getRuntime().availableProcessors();
    ExecutorService service = Executors.newFixedThreadPool(poolSize);
    List<Future<?>> futures = new LinkedList<Future<?>>();
    for (int k = 0; k < numPointFiles; k++) {

        Future<?> f = service
                .submit(new DataGenMMDense(pointsPerFile, localInputDir, Integer.toString(k), vectorSize));

        futures.add(f); // add a new thread
    }
    for (Future<?> f : futures) {
        f.get();
    }
    // Shut down the executor service so that this
    // thread can exit
    service.shutdownNow();
    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);
    DeleteFileFolder(localInputDir);
}

From source file:Main.java

/**
 * Creates a new and empty directory in the default temp directory using the
 * given prefix. This methods uses {@link File#createTempFile} to create a
 * new tmp file, deletes it and creates a directory for it instead.
 * //from   ww w. j  a v  a2 s .  c  om
 * @param prefix The prefix string to be used in generating the diretory's
 * name; must be at least three characters long.
 * @return A newly-created empty directory.
 * @throws IOException If no directory could be created.
 */
public static File createTempDir(String prefix) throws IOException {
    String tmpDirStr = System.getProperty("java.io.tmpdir");
    if (tmpDirStr == null) {
        throw new IOException("System property 'java.io.tmpdir' does not specify a tmp dir");
    }

    File tmpDir = new File(tmpDirStr);
    if (!tmpDir.exists()) {
        boolean created = tmpDir.mkdirs();
        if (!created) {
            throw new IOException("Unable to create tmp dir " + tmpDir);
        }
    }

    File resultDir = null;
    int suffix = (int) System.currentTimeMillis();
    int failureCount = 0;
    do {
        resultDir = new File(tmpDir, prefix + suffix % 10000);
        suffix++;
        failureCount++;
    } while (resultDir.exists() && failureCount < 50);

    if (resultDir.exists()) {
        throw new IOException(
                failureCount + " attempts to generate a non-existent directory name failed, giving up");
    }
    boolean created = resultDir.mkdir();
    if (!created) {
        throw new IOException("Failed to create tmp directory");
    }

    return resultDir;
}

From source file:io.Tools.java

/**
 * Create test PDB and Chemcomp folder. Also all PDB files in resources are copied there so all test can use this
 * folder//ww w.  j a va 2s .com
 *
 * @return
 */
public static String createPermanentTestFolder() {

    String d = System.getProperty("user.home");
    String builtTestFolder = d + File.separator + "Documents" + File.separator + testFolderName
            + File.separator;
    final File baseDir = new File(builtTestFolder);

    String builttestPDBFolder = builtTestFolder + File.separator + "pdb";
    baseDir.mkdirs();
    final File pdbDir = new File(builttestPDBFolder);
    if (Files.exists(Paths.get(builttestPDBFolder))) {
        try {
            FileUtils.deleteDirectory(pdbDir);
        } catch (IOException e) {
        }
    }
    pdbDir.mkdir();

    String builttestChemcompFolder = builtTestFolder + File.separator + "chemcomp";
    final File chemcompDir = new File(builttestChemcompFolder);
    if (Files.exists(Paths.get(builttestChemcompFolder))) {
        try {
            FileUtils.deleteDirectory(chemcompDir);
        } catch (IOException e) {
        }
    }

    chemcompDir.mkdirs();

    pdbDir.mkdir();
    testChemcompFolder = builtTestFolder;
    testPDBFolder = builttestPDBFolder;

    String resourcesPDBFolder = null;
    try {
        URL url = BiojavaReaderFromPDBFolderTest.class.getClassLoader().getResource("pdb/1di9.cif.gz");
        File pdb1di9file = new File(url.toURI());
        resourcesPDBFolder = pdb1di9file.getParent();
        Map<String, List<MMcifFileInfos>> indexPDBFileInFolder = IOTools
                .indexPDBFileInFolder(new File(resourcesPDBFolder).toString());
        for (Map.Entry<String, List<MMcifFileInfos>> entry : indexPDBFileInFolder.entrySet()) {
            try {
                FileUtils.copyFileToDirectory(new File(entry.getValue().get(0).getPathToFile().toString()),
                        pdbDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    String resourcesChemcompFolder = null;
    try {
        URL url = BiojavaReaderFromPDBFolderTest.class.getClassLoader().getResource("chemcomp/0DY.cif.gz");
        File chemcomp0DY = new File(url.toURI());
        resourcesChemcompFolder = chemcomp0DY.getParent();
        Map<String, List<Path>> indexPDBFileInFolder = IOTools
                .indexChemcompFileInFolder(new File(resourcesChemcompFolder).toString());
        for (Map.Entry<String, List<Path>> entry : indexPDBFileInFolder.entrySet()) {
            try {
                FileUtils.copyFileToDirectory(new File(entry.getValue().get(0).toString()),
                        new File(builttestChemcompFolder));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return testChemcompFolder;
}

From source file:com.google.appinventor.buildserver.ProjectBuilder.java

/**
 * Creates a new directory beneath the system's temporary directory (as
 * defined by the {@code java.io.tmpdir} system property), and returns its
 * name. The name of the directory will contain the current time (in millis),
 * and a random number./*ww w.jav  a2 s  .  c  o m*/
 *
 * <p>This method assumes that the temporary volume is writable, has free
 * inodes and free blocks, and that it will not be called thousands of times
 * per second.
 *
 * @return the newly-created directory
 * @throws IllegalStateException if the directory could not be created
 */
private static File createNewTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    String baseNamePrefix = System.currentTimeMillis() + "_" + Math.random() + "-";

    final int TEMP_DIR_ATTEMPTS = 10000;
    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
        File tempDir = new File(baseDir, baseNamePrefix + counter);
        if (tempDir.exists()) {
            continue;
        }
        if (tempDir.mkdir()) {
            return tempDir;
        }
    }
    throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS
            + " attempts (tried " + baseNamePrefix + "0 to " + baseNamePrefix + (TEMP_DIR_ATTEMPTS - 1) + ')');
}

From source file:com.github.DroidPHP.ServerUtils.java

final private static void restoreOrCreateServerData() {

    File mFile = new File(getHttpDirectory() + "/conf/");
    if (!mFile.exists())
        mFile.mkdirs();/*from w w w .java 2  s. c  o  m*/

    mFile = new File(getHttpDirectory() + "/www/");

    if (!mFile.exists())
        mFile.mkdir();

    mFile = new File(getHttpDirectory() + "/logs/");

    if (!mFile.exists())
        mFile.mkdir();
    mFile = new File(getHttpDirectory() + "/tmp/");

    if (!mFile.exists())
        mFile.mkdir();

    mFile = null;

}

From source file:net.sourceforge.doddle_owl.utils.Utils.java

public static File getENWNFile() {
    File wnDir = new File(TEMP_DIR + DODDLEConstants.ENWN_HOME);
    if (wnDir.exists()) {
        // System.out.println("exist: " + wnDir.getAbsolutePath());
        return wnDir;
    }//from   w w  w  .j a  va 2  s  .  com
    wnDir.mkdir();
    String[] wnFiles = { "adj.exc", "adv.exc", "cntlist", "cntlist.rev", "data.adj", "data.noun", "data.verb",
            "frames.vrb", "index.adj", "index.adv", "index.noun", "index.sense", "index.verb", "lexnames",
            "log.grind.3.0", "noun.exc", "sentidx.vrb", "sents.vrb", "verb.exc", "verb.Framestext" };
    for (String wnf : wnFiles) {
        URL url = DODDLE_OWL.class.getClassLoader().getResource(RESOURCE_DIR + DODDLEConstants.ENWN_HOME + wnf);
        try {
            File f = new File(wnDir.getAbsolutePath() + File.separator + wnf);
            if (url != null) {
                FileUtils.copyURLToFile(url, f);
            }
            // System.out.println("copy: " + f.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // System.out.println("created: " + wnDir.getAbsolutePath());
    return wnDir;
}