Example usage for java.io File list

List of usage examples for java.io File list

Introduction

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

Prototype

public String[] list() 

Source Link

Document

Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

Usage

From source file:morphy.utils.FileUtils.java

/**
 * Deletes all files and subdirectories under "dir".
 * //from   w  w  w  . j ava  2  s.  c o  m
 * @param dir
 *            Directory to be deleted
 * @return boolean Returns "true" if all deletions were successful. If a
 *         deletion fails, the method stops attempting to delete and returns
 *         "false".
 */
public static boolean deleteDir(File dir) {

    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so now it can be smoked
    return dir.delete();
}

From source file:Compress.java

/** Zip the contents of the directory, and save it in the zipfile */
public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
        throw new IllegalArgumentException("Compress: not a directory:  " + dir);
    String[] entries = d.list();
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytes_read;

    // Create a stream to compress data and write it to the zipfile
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    // Loop through all entries in the directory
    for (int i = 0; i < entries.length; i++) {
        File f = new File(d, entries[i]);
        if (f.isDirectory())
            continue; // Don't zip sub-directories
        FileInputStream in = new FileInputStream(f); // Stream to read file
        ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        while ((bytes_read = in.read(buffer)) != -1)
            // Copy bytes
            out.write(buffer, 0, bytes_read);
        in.close(); // Close input stream
    }/* w ww.  j a  va 2 s.  c  o  m*/
    // When we're done with the whole loop, close the output stream
    out.close();
}

From source file:demo.utils.MiniClusterUtils.java

public static void startMiniCluster() {
    if (clusterLauncher != null) {
        throw new IllegalStateException("MiniClustrer is currently running");
    }//  w  w w.  j  av a2s. com
    File file = new File(System.getProperty("user.dir"));
    Path path = Paths.get(file.getAbsolutePath());
    Path parentPath = path.getParent();
    String[] resources = file.list();
    for (String resource : resources) {
        if (resource.equals("yaya-demo")) {
            parentPath = path;
            break;
        }
    }
    File miniClusterExe = new File(
            parentPath.toString() + "/yarn-test-cluster/build/install/yarn-test-cluster/bin/yarn-test-cluster");
    System.out.println(miniClusterExe.getAbsolutePath());
    if (!miniClusterExe.exists()) {
        logger.info("BUILDING MINI_CLUSTER");
        CommandProcessLauncher buildLauncher = new CommandProcessLauncher(
                path.toString() + "/build-mini-cluster");
        buildLauncher.launch();
    }
    Assert.isTrue(miniClusterExe.exists(), "Failed to find mini-cluster executable");
    clusterLauncher = new CommandProcessLauncher(miniClusterExe.getAbsolutePath());
    executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            logger.info("STARTING MINI_CLUSTER");
            clusterLauncher.launch();
        }
    });
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

From source file:com.dc.util.file.FileSupport.java

public static void copyAllFiles(String sourcePath, String destPath) throws IOException {
    File s = new File(sourcePath);
    String[] files = s.list();
    for (String file : files) {
        String sourceFile = sourcePath + "/" + file;
        File destination = new File(destPath + "/" + file);
        InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
        copy(is, destination);/*from ww w.j  a va2 s. co m*/
    }
}

From source file:com.ltb.Main.java

public static void displayIt(File node) throws IOException, InterruptedException {
    String filePath = node.getAbsoluteFile().getAbsolutePath();
    System.out.println(filePath);

    if (node.isDirectory()) {
        String[] subNote = node.list();
        for (String filename : subNote) {
            displayIt(new File(node, filename));
        }//w w  w .  j ava2  s.  c  o m
    } else {

        //Process pr = Runtime.getRuntime().exec("avconv -i //home//juanma//Videos//License.avi"); // Working fine
        //Process pr = Runtime.getRuntime().exec(outLine); // Working fine without spaces
        String[] args1 = { "avconv", "-i", filePath };
        Process pr = Runtime.getRuntime().exec(args1);
        //filePath = filePath.replace("/" , "//");
        //filePath = filePath.replace(" " , "\\ ");
        //String commandline ="avconv -i \""+filePath+"\"";
        //String commandline ="avconv -i "+filePath;
        //Process pr = Runtime.getRuntime().exec(commandline);

        BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        //BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line;
        // Start FilmFactory
        String extension = FilenameUtils.getExtension(node.getName());
        if (isFilmExtension(extension) == false) {
            return;
        } else {

            Film film = new Film(node.getName(), filePath);
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                if (line.contains("Invalid data")) {
                    // TODO Most probably no film - Change method below
                    film.isNotFilm();
                } else if (line.contains("Audio")) {
                    film.addAudioTrack(line);
                } else if (line.contains("No such file")) {
                    System.out.println("Error?");
                }

            }
            pr.waitFor();
            in.close();
        }
    }

}

From source file:Main.java

/**
 * Removes the directory.// w  ww.j  a v  a 2  s  .  co  m
 * 
 * @param directory
 *            the directory
 * @return true, if successful
 */
public static boolean removeDirectory(File directory) {

    if (directory == null) {
        return false;
    }
    if (!directory.exists()) {
        return true;
    }
    if (directory.isDirectory()) {
        final String[] list = directory.list();
        // Some JVMs return null for File.list() when the
        // directory is empty.
        if (list != null) {
            for (final String element : list) {
                final File entry = new File(directory, element);
                if (entry.isDirectory()) {
                    if (!removeDirectory(entry)) {
                        return false;
                    }
                } else {
                    if (!entry.delete()) {
                        return false;
                    }
                }
            }
        }
    }
    return directory.delete();
}

From source file:com.tinspx.util.io.callbacks.FileTests.java

public static File setupTestDir() throws IOException {
    File testDir = new File(new File(System.getProperty("user.dir")), "test");
    if (testDir.exists()) {
        if (testDir.list().length > 0) {
            throw new IOException(testDir + " exists and is not empty");
        }//from   w ww .  j a  v a 2 s. co  m
    } else if (!testDir.mkdirs()) {
        throw new IOException("could not create " + testDir);
    }
    return testDir;
    //        boolean complete = false;
    //        try {
    //            Resources.asByteSource(ChannelSource.class.getResource("/" + FORMATTED)).copyTo(Files.asByteSink(new File(testDir, FORMATTED)));
    //            Resources.asByteSource(ChannelSource.class.getResource("/" + SAMPLE)).copyTo(Files.asByteSink(new File(testDir, SAMPLE)));
    //            complete = true;
    //            return testDir;
    //        } finally {
    //            if(!complete) {
    //                teardownTestDir(testDir).close();
    //            }
    //        }
}

From source file:cn.org.once.cstack.utils.FilesUtils.java

public static void deleteDirectory(File file) throws IOException {

    if (file.isDirectory()) {

        // directory is empty, then delete it
        if (file.list().length == 0) {

            file.delete();// w  w  w . jav a2  s.  co m

        } else {

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

            for (String temp : files) {
                // construct the file structure
                File fileDelete = new File(file, temp);

                // recursive delete
                deleteDirectory(fileDelete);
            }

            // check the directory again, if empty then delete it
            if (file.list().length == 0) {
                file.delete();
            }
        }

    } else {
        // if file, then delete it
        file.delete();
    }
}

From source file:com.appeligo.config.ConfigurationService.java

private synchronized static AbstractConfiguration loadConfiguration(String configuration) {
    if (log.isInfoEnabled()) {
        log.info("Loading AbstractConfiguration under: " + rootDir);
    }/*from   w w  w .  j a v a 2  s. c  o  m*/
    AbstractConfiguration ac = configMap.get(configuration);
    if (ac != null) {
        return ac;
    }

    File envDir = new File(rootDir, envName);
    File baseDir = new File(rootDir, baseName);

    String[] environmentList = envDir.list();
    String envConfiguration = configuration;
    if (contains(environmentList, configuration + ".xml")) {
        envConfiguration += ".xml";
    } else {
        envConfiguration += ".properties";
    }
    String[] baseList = baseDir.list();
    String baseConfiguration = configuration;
    if (contains(baseList, configuration + ".xml")) {
        baseConfiguration += ".xml";
    } else {
        baseConfiguration += ".properties";
    }

    File envFile = new File(rootDir, envName + "/" + envConfiguration);
    File baseFile = new File(rootDir, baseName + "/" + baseConfiguration);
    ac = createConfig(envFile, baseFile);
    configMap.put(configuration, ac);
    return ac;
}

From source file:com.glaf.core.config.CustomProperties.java

public static void reload() {
    if (!loading.get()) {
        InputStream inputStream = null;
        try {/*from  w ww .  j a va2 s.c  o  m*/
            loading.set(true);
            String config = SystemProperties.getConfigRootPath() + "/conf/props";
            logger.debug(config);
            File directory = new File(config);
            if (directory.exists()) {
                String[] filelist = directory.list();
                if (filelist != null) {
                    for (int i = 0, len = filelist.length; i < len; i++) {
                        String filename = config + "/" + filelist[i];
                        logger.debug(filename);
                        File file = new File(filename);
                        if (file.isFile() && file.getName().endsWith(".properties")) {
                            logger.info("load properties:" + file.getAbsolutePath());
                            inputStream = new FileInputStream(file);
                            Properties p = PropertiesUtils.loadProperties(inputStream);
                            if (p != null) {
                                Enumeration<?> e = p.keys();
                                while (e.hasMoreElements()) {
                                    String key = (String) e.nextElement();
                                    String value = p.getProperty(key);
                                    properties.setProperty(key, value);
                                    properties.setProperty(key.toLowerCase(), value);
                                    properties.setProperty(key.toUpperCase(), value);
                                }
                            }
                            IOUtils.closeStream(inputStream);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            loading.set(false);
            IOUtils.closeStream(inputStream);
        }
    }
}