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:edu.iu.daal_svd.SVDUtil.java

/**
 * Generate data and upload to the data dir.
 * //from  w w  w . ja  v a 2  s . c  o 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 DataGenRunnable(
        //     pointsPerFile, localInputDir, Integer
        //       .toString(k), vectorSize));
        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:com.owncloud.android.utils.PushUtils.java

private static int generateRsa2048KeyPair() {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;//from   w  ww.j  a  v  a2  s  . c  om

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
    File keyPathFile = new File(keyPath);

    if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
        try {
            if (!keyPathFile.exists()) {
                keyPathFile.mkdir();
            }
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);

            KeyPair pair = keyGen.generateKeyPair();
            int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
            int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);

            if (statusPrivate == 0 && statusPublic == 0) {
                // all went well
                return 0;
            } else {
                return -2;
            }
        } catch (NoSuchAlgorithmException e) {
            Log_OC.d(TAG, "RSA algorithm not supported");
        }
    } else {
        // we already have the key
        return -1;
    }

    // we failed to generate the key
    return -2;
}

From source file:iics.Connection.java

static void create_dir() {

    try {//from w  w w . ja  v  a 2  s  . co  m
        File directory = new File(dir);
        if (directory.exists()) {
            create_file();

        } else {
            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();
            if (success) {
                create_file();
            } else {
                System.out.printf("Failed to create new directory: %s%n", dir);
                JOptionPane.showMessageDialog(null,
                        "                 An error occured!! \n Contact your system admin for help.", null,
                        JOptionPane.WARNING_MESSAGE);
                close_loda();
            }
        }
        fw = new FileWriter(f.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    } catch (IOException ex) {
        //   Logger.getLogger(Extract.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null,
                "                 An error occured!! \n Contact your system admin for help.", null,
                JOptionPane.WARNING_MESSAGE);
        close_loda();
    } finally {
        try {
            fw.close();
        } catch (IOException ex) {
            //   Logger.getLogger(Extract.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null,
                    "                 An error occured!! \n Contact your system admin for help.", null,
                    JOptionPane.WARNING_MESSAGE);
            close_loda();
        }
    }
}

From source file:de.ingrid.portal.portlets.admin.AdminPortalProfilePortlet.java

/**
 * Copy directory to file system.//  ww w. ja  v a 2 s.  co  m
 * 
 * @param source
 * @param dest
 * @throws IOException
 */
private static void copyDir(String source, String dest) throws IOException {
    File sourceDir = new File(source);
    File destDir = new File(dest);
    File[] sourceFiles = sourceDir.listFiles();

    if (!destDir.exists()) {
        if (sourceDir != null) {
            if (sourceDir.isDirectory()) {
                destDir.mkdir();
            }
        }
    }

    for (int i = 0; i < sourceFiles.length; i++) {
        File sourceFile = sourceFiles[i];
        File destFile = new File(dest.concat("/").concat(sourceFile.getName()));

        if (sourceFile.isDirectory()) {
            copyDir(sourceFile.getAbsolutePath(), destFile.getAbsolutePath());
        } else {
            copy(sourceFile, destFile);
        }
    }
}

From source file:dk.netarkivet.common.utils.ZipUtils.java

/** Unzip a zipFile into a directory.  This will create subdirectories
 * as needed./*from www.ja  v a2 s  . co  m*/
 *
 * @param zipFile The file to unzip
 * @param toDir The directory to create the files under.  This directory
 * will be created if necessary.  Files in it will be overwritten if the
 * filenames match.
 */
public static void unzip(File zipFile, File toDir) {
    ArgumentNotValid.checkNotNull(zipFile, "File zipFile");
    ArgumentNotValid.checkNotNull(toDir, "File toDir");
    ArgumentNotValid.checkTrue(toDir.getAbsoluteFile().getParentFile().canWrite(),
            "can't write to '" + toDir + "'");
    ArgumentNotValid.checkTrue(zipFile.canRead(), "can't read '" + zipFile + "'");
    InputStream inputStream = null;
    ZipFile unzipper = null;
    try {
        try {
            unzipper = new ZipFile(zipFile);
            Enumeration<? extends ZipEntry> entries = unzipper.entries();
            while (entries.hasMoreElements()) {
                ZipEntry ze = entries.nextElement();
                File target = new File(toDir, ze.getName());
                // Ensure that its dir exists
                FileUtils.createDir(target.getCanonicalFile().getParentFile());
                if (ze.isDirectory()) {
                    target.mkdir();
                } else {
                    inputStream = unzipper.getInputStream(ze);
                    FileUtils.writeStreamToFile(inputStream, target);
                    inputStream.close();
                }
            }
        } finally {
            if (unzipper != null) {
                unzipper.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Failed to unzip '" + zipFile + "'", e);
    }
}

From source file:com.glaf.core.util.FileUtils.java

public static boolean mkdirsWithExistsCheck(File dir) {
    if (dir.mkdir() || dir.exists()) {
        return true;
    }//from   w  ww.j a  v a2 s .c  o  m
    File canonDir = null;
    try {
        canonDir = dir.getCanonicalFile();
    } catch (IOException e) {
        return false;
    }
    String parent = canonDir.getParent();
    return (parent != null)
            && (mkdirsWithExistsCheck(new File(parent)) && (canonDir.mkdir() || canonDir.exists()));
}

From source file:net.mybox.mybox.Common.java

/**
 * Creates the directory if it does not exist
 * @return true if the directory exists when the function returns, else false
 *//* w ww.ja  va 2s. c  o m*/
public static boolean MakeDir(String dirpath) {

    File baseDir = new File(dirpath);

    if (!baseDir.exists())
        if (!baseDir.mkdir())
            return false;

    return true;
}

From source file:org.fcrepo.test.api.TestHTTPStatusCodes.java

private static void addSystemWidePolicyFile(String filename, String xml) throws Exception {
    final String policyDir = "data/fedora-xacml-policies/repository-policies/junit";
    File dir = new File(FEDORA_HOME, policyDir);
    dir.mkdir();// w ww  . j a va2s . co  m
    File policyFile = new File(dir, filename);
    writeStringToFile(xml, policyFile);
}

From source file:ca.uhn.hl7v2.sourcegen.SourceGenerator.java

/**
 * Creates the given directory if it does not exist.
 *///from  w w  w  .  ja v  a2s  .com
public static File makeDirectory(String directory) throws IOException {
    StringTokenizer tok = new StringTokenizer(directory, "\\/", false);

    File currDir = directory.startsWith("/") ? new File("/") : null;
    while (tok.hasMoreTokens()) {
        String thisDirName = tok.nextToken();

        currDir = new File(currDir, thisDirName); //if currDir null, defaults to 1 arg call

        if (!currDir.exists()) {
            //create
            currDir.mkdir();
            ;
        } else if (currDir.isFile()) {
            throw new IOException("Can't create directory " + thisDirName + " - file with same name exists.");
        }
    }

    return currDir;
}

From source file:com.netspective.axiom.TestUtils.java

static public void setupDb(String connProviderId, boolean createDb, boolean loadData) {
    Log log = LogFactory.getLog(TestUtils.class);

    Set connContextsWithOpenConnections = new HashSet(
            AbstractConnectionContext.getConnectionContextsWithOpenConnections());

    for (Iterator i = connContextsWithOpenConnections.iterator(); i.hasNext();) {
        ConnectionContext cc = (ConnectionContext) i.next();

        cc.rollbackAndCloseAndLogAsConnectionLeak(log, null);
    }/*  ww w  .  ja va 2 s.  c  o m*/

    String classDir = connProviderId.replace('.', '/');

    FileFind.FileFindResults ffr = FileFind.findInClasspath(classDir + "/" + schemaFilename,
            FileFind.FINDINPATHFLAG_SEARCH_RECURSIVELY);
    if (!ffr.isFileFound()) {
        ffr = FileFind.findInClasspath(classDir + "-" + schemaFilename,
                FileFind.FINDINPATHFLAG_SEARCH_RECURSIVELY);
    }

    if (!ffr.isFileFound()) {
        return;
    }

    File schemaFile = ffr.getFoundFile();
    String rootPath = schemaFile.getParentFile().getAbsolutePath();

    Project project = new Project();

    Target target = new Target();
    target.setName("generate-ddl");

    AxiomTask task = new AxiomTask();
    task.setTaskName("generate-ddl");
    task.setSchema("db");
    task.setDdl("*");
    task.setProjectFile(new File(rootPath + "/" + schemaFilename));
    task.setDestDir(new File(rootPath + ddlPath));

    target.addTask(task);
    project.addTarget(target);
    task.setProject(project);

    SqlManager manager = task.getSqlManager();
    task.generateDdlFiles(manager);

    if (!createDb)
        return;

    SQLExec sqlExec = new SQLExec();
    target.addTask(sqlExec);
    sqlExec.setProject(project);
    File dbFolder = new File(rootPath + dbPath);

    //need to do a recursive delete or call the deleteTree ant task
    Delete del = new Delete();
    target.addTask(del);
    del.setProject(project);
    del.setDir(dbFolder);
    del.execute();

    dbFolder.mkdir();

    sqlExec.setSrc(new File(rootPath + ddlPath + "/db-hsqldb.sql"));
    sqlExec.setDriver("org.hsqldb.jdbcDriver");
    sqlExec.setUrl("jdbc:hsqldb:" + rootPath + dbPath + "/" + dbName);
    sqlExec.setUserid("sa");
    sqlExec.setPassword("");
    sqlExec.execute();

    //TODO: If we ever need to generate the DAL, then the trick is how to compile the classes that use it.
    //      For now, we leve it here for code coverage purposes, since it is excercising the DAL Generator
    String testRoot = rootPath.substring(0, rootPath.length() - connProviderId.length() - 1);
    task.setDestDir(new File(testRoot));
    task.setDalPackage(connProviderId + ".dal");
    task.generateDalFiles(manager);

    if (!loadData)
        return;

    task.setImport(new File(rootPath + "/" + dataImportFile));
    task.setDtdFile(new File(rootPath + dataImportDtdFile));
    task.generateImportDtd(manager);

    task.setDriver("org.hsqldb.jdbcDriver");
    task.setUrl("jdbc:hsqldb:" + rootPath + dbPath + "/" + dbName);
    task.setUserId("sa");
    task.setPassword("");
    task.importData(manager);

    connProvider.addDataSourceInfo(connProviderId, "org.hsqldb.jdbcDriver",
            "jdbc:hsqldb:" + rootPath + dbPath + File.separator + dbName, "sa", "");

}