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:com.centeractive.ws.builder.soap.SchemaUtils.java

private static void loadSchemaDirectory(String schemaDirectory) throws IOException, MalformedURLException {
    File dir = new File(schemaDirectory);
    if (dir.exists() && dir.isDirectory()) {
        String[] xsdFiles = dir.list();
        int cnt = 0;

        if (xsdFiles != null && xsdFiles.length > 0) {
            for (int c = 0; c < xsdFiles.length; c++) {
                try {
                    String xsdFile = xsdFiles[c];
                    if (xsdFile.endsWith(".xsd")) {
                        String filename = schemaDirectory + File.separator + xsdFile;
                        loadDefaultSchema(new URL("file:" + filename));
                        cnt++;/* w w w. java 2s  .  co m*/
                    }
                } catch (Throwable e) {
                    throw new SoapBuilderException(e);
                }
            }
        }

        if (cnt == 0)
            log.warn("Missing schema files in  schemaDirectory [" + schemaDirectory + "]");
    } else
        log.warn("Failed to open schemaDirectory [" + schemaDirectory + "]");
}

From source file:com.polyvi.xface.util.XFileUtils.java

/**
 * //from www  . j a va2 s.c o  m
 *
 * @param path
 *            /
 */
public static boolean deleteFileRecursively(String path) {
    File destFile = new File(path);
    if (!destFile.exists()) {
        return true;
    }

    if (destFile.isFile()) {
        destFile.delete();
        return true;
    }

    String[] childNames = destFile.list();
    for (String child : childNames) {
        if (!deleteFileRecursively(new File(path, child).getAbsolutePath())) {
            return false;
        }
    }
    return destFile.delete();
}

From source file:com.wegas.core.Helper.java

/**
 * @param file/*from ww w.  j  a v  a 2s .c  o  m*/
 * @throws IOException
 */
public static void recursiveDelete(File file) throws IOException {
    if (file.isDirectory()) {
        if (file.list().length == 0) {
            if (!file.delete()) {
                logger.warn("Failed to delete file {}", file.getName());
            }
        } else {
            String files[] = file.list();
            for (String f : files) {
                File fileToDel = new File(file, f);
                recursiveDelete(fileToDel);
            }
            if (file.list().length == 0) {
                if (!file.delete()) {
                    logger.warn("Failed to delete file {}", file.getName());
                }
            } else {
                throw new IOException("Could not empty " + file.getName());
            }
        }

    } else if (!file.delete()) {
        logger.warn("Failed to delete file {}", file.getName());
    }
}

From source file:com.edgenius.core.util.ZipFileUtil.java

/**
 * Creates a ZIP file and places it in the current working directory. The zip file is compressed
 * at the default compression level of the Deflater.
 * /*from www .ja  va  2  s  .c  o  m*/
 * @param listToZip. Key is file or directory, value is parent directory which will remove from given file/directory because 
 * compression only save relative directory.  For example, c:\geniuswiki\data\repository\somefile, if value is c:\geniuswiki, then only 
 * \data\repository\somefile will be saved.  It is very important, the value must be canonical path, ie, c:\my document\geniuswiki, 
 * CANNOT like this "c:\my doc~1\" 
 * 
 * 
 */
public static void createZipFile(String zipFileName, Map<File, String> listToZip, boolean withEmptyDir)
        throws ZipFileUtilException {
    ZipOutputStream zop = null;
    try {
        zop = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
        zop.setMethod(ZipOutputStream.DEFLATED);
        zop.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (Entry<File, String> entry : listToZip.entrySet()) {
            File file = entry.getKey();
            if (!file.exists()) {
                log.warn("Unable to find file " + file + " to zip");
                continue;
            }
            if (file.isDirectory()) {
                Collection<File> list = FileUtils.listFiles(file, null, true);
                for (File src : list) {
                    addEntry(zop, src, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                }
                if (withEmptyDir) {
                    final List<File> emptyDirs = new ArrayList<File>();
                    if (file.list().length == 0) {
                        emptyDirs.add(file);
                    } else {
                        //I just don't know how quickly to find out all empty sub directories recursively. so use below hack:
                        FileUtils.listFiles(file, FileFilterUtils.falseFileFilter(), new IOFileFilter() {
                            //JDK1.6 @Override
                            public boolean accept(File f) {
                                if (!f.isDirectory())
                                    return false;

                                int size = f.listFiles().length;
                                if (size == 0) {
                                    emptyDirs.add(f);
                                }
                                return true;
                            }

                            //JDK1.6 @Override
                            public boolean accept(File arg0, String arg1) {
                                return true;
                            }
                        });
                    }
                    for (File src : emptyDirs) {
                        addEntry(zop, null, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                    }
                }
            } else {
                addEntry(zop, file, createRelativeDir(file.getCanonicalPath(), entry.getValue()));
            }

        }
    } catch (IOException e1) {
        throw new ZipFileUtilException(
                "An error has occurred while trying to zip the files. Error message is: ", e1);
    } finally {
        try {
            if (zop != null)
                zop.close();
        } catch (Exception e) {
        }
    }

}

From source file:net.kamhon.ieagle.util.ReflectionUtil.java

/**
 * <pre>//  w ww.  j  a v a2 s . co m
 * This method finds all classes that are located in the package identified by
 * the given
 * &lt;code&gt;
 * packageName
 * &lt;/code&gt;
 * .
 * &lt;br&gt;
 * &lt;b&gt;ATTENTION:&lt;/b&gt;
 * &lt;br&gt;
 * This is a relative expensive operation. Depending on your classpath
 * multiple directories,JAR, and WAR files may need to scanned.
 * 
 * &#064;param packageName is the name of the {@link Package} to scan.
 * &#064;param includeSubPackages - if
 * &lt;code&gt;
 * true
 * &lt;/code&gt;
 *  all sub-packages of the
 *        specified {@link Package} will be included in the search.
 * &#064;return a {@link Set} will the fully qualified names of all requested
 *         classes.
 * &#064;throws IOException if the operation failed with an I/O error.
 * &#064;see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java
 * </pre>
 */
public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern,
        String... endWiths) throws IOException {

    Set<String> classSet = new HashSet<String>();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = packageName.replace('.', '/');
    String pathWithPrefix = path + '/';
    Enumeration<URL> urls = classLoader.getResources(path);
    StringBuilder qualifiedNameBuilder = new StringBuilder(packageName);
    qualifiedNameBuilder.append('.');

    int qualifiedNamePrefixLength = qualifiedNameBuilder.length();

    while (urls.hasMoreElements()) {

        URL packageUrl = urls.nextElement();
        String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8");
        String protocol = packageUrl.getProtocol().toLowerCase();
        log.debug(urlString);

        if ("file".equals(protocol)) {

            File packageDirectory = new File(urlString);

            if (packageDirectory.isDirectory()) {
                if (includeSubPackages) {
                    findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder,
                            qualifiedNamePrefixLength, packagePattern);
                } else {
                    for (String fileName : packageDirectory.list()) {
                        String simpleClassName = fixClassName(fileName);
                        if (simpleClassName != null) {
                            qualifiedNameBuilder.setLength(qualifiedNamePrefixLength);
                            qualifiedNameBuilder.append(simpleClassName);
                            if (qualifiedNameBuilder.toString().matches(packagePattern))
                                classSet.add(qualifiedNameBuilder.toString());
                        }
                    }
                }
            }
        } else if ("jar".equals(protocol)) {
            // somehow the connection has no close method and can NOT be
            // disposed
            JarURLConnection connection = (JarURLConnection) packageUrl.openConnection();
            JarFile jarFile = connection.getJarFile();
            Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
            while (jarEntryEnumeration.hasMoreElements()) {
                JarEntry jarEntry = jarEntryEnumeration.nextElement();
                String absoluteFileName = jarEntry.getName();
                // if (absoluteFileName.endsWith(".class")) { //original
                if (endWith(absoluteFileName, endWiths)) { // modified
                    if (absoluteFileName.startsWith("/")) {
                        absoluteFileName.substring(1);
                    }
                    // special treatment for WAR files...
                    // "WEB-INF/lib/" entries should be opened directly in
                    // contained jar
                    if (absoluteFileName.startsWith("WEB-INF/classes/")) {
                        // "WEB-INF/classes/".length() == 16
                        absoluteFileName = absoluteFileName.substring(16);
                    }
                    boolean accept = true;
                    if (absoluteFileName.startsWith(pathWithPrefix)) {
                        String qualifiedName = absoluteFileName.replace('/', '.');
                        if (!includeSubPackages) {
                            int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1);
                            if (index != -1) {
                                accept = false;
                            }
                        }
                        if (accept) {
                            String className = fixClassName(qualifiedName);

                            if (className != null) {
                                if (qualifiedNameBuilder.toString().matches(packagePattern))
                                    classSet.add(className);
                            }
                        }
                    }
                }
            }
        } else {
            log.debug("unknown protocol -> " + protocol);
        }
    }
    return classSet;
}

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

public static void init() {
    if (!loading.get()) {
        try {/* w  ww  .ja  v  a  2s  .co  m*/
            loading.set(true);
            String config = SystemProperties.getConfigRootPath() + "/conf/templates/jdbc";
            File directory = new File(config);
            if (directory.exists() && directory.isDirectory()) {
                String[] filelist = directory.list();
                if (filelist != null) {
                    for (int i = 0, len = filelist.length; i < len; i++) {
                        String filename = config + "/" + filelist[i];
                        File file = new File(filename);
                        if (file.isFile() && file.getName().endsWith(".properties")) {
                            InputStream inputStream = new FileInputStream(file);
                            Properties props = PropertiesUtils.loadProperties(inputStream);
                            if (props != null) {
                                jdbcTemplateProperties.put(props.getProperty(JDBC_NAME), props);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        } finally {
            loading.set(false);
        }
    }
}

From source file:isl.FIMS.utils.Utils.java

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean deleted = deleteDir(new File(dir, children[i]));
            if (!deleted) {
                return false;
            }/* ww w . j av a 2 s  . c  o m*/
        }
    }
    return dir.delete();
}

From source file:edu.stanford.muse.launcher.Splash.java

public static boolean deleteDir(File f) {
    if (f.isDirectory()) {
        String[] children = f.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(f, children[i]));
            if (!success) {
                System.err.println("warning: failed to delete file " + f);
                return false;
            }/*from  w w w. j  a  v a2 s .co m*/
        }
    }

    // The directory is now empty so delete it
    return f.delete();
}

From source file:dk.statsbiblioteket.util.Files.java

/**
 * Delete the file or directory given by <code>path</code> (recursively if
 * <code>path</code> is a directory).
 *
 * @param path a {@link File} representing the file or directory to be
 *             deleted./*from  ww w .  ja  v a  2s. c  om*/
 * @throws IOException if the path doesn't exist or could not be deleted.
 */
public static void delete(File path) throws IOException {
    log.trace("delete(" + path + ") called");
    if (!path.exists()) {
        throw new FileNotFoundException(path.toString());
    }
    if (path.isFile()) {
        if (!path.delete()) {
            throw new IOException("Could not delete the file '" + path + "'");
        }
        return;
    }
    for (String child : path.list()) {
        delete(new File(path, child));
    }
    if (!path.delete()) {
        throw new IOException("Could not delete the folder '" + path + "'");
    }
}

From source file:com.photon.phresco.service.impl.RepositoryManagerImpl.java

public static boolean removeDirectory(File directory) {
    if (directory == null)
        return false;
    if (!directory.exists())
        return true;
    if (!directory.isDirectory())
        return false;

    String[] list = directory.list();

    // Some JVMs return null for File.list() when the
    // directory is empty.
    if (list != null) {
        for (int i = 0; i < list.length; i++) {
            File entry = new File(directory, list[i]);
            if (entry.isDirectory()) {
                if (!removeDirectory(entry))
                    return false;
            } else {
                if (!entry.delete())
                    return false;
            }/* w ww .j  a  v  a  2s .  co m*/
        }
    }

    return directory.delete();
}