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.cloudera.sqoop.shims.ShimLoader.java

/**
 * Look through the shim directory for a jar matching 'jarPattern'
 * and classload it./*ww  w .  j a  v a 2s  .  c  om*/
 * @param jarPattern a regular expression which the shim jar's filename
 * must match.
 * @param className a class to classload from the jar.
 */
private static void loadMatchingShimJar(String jarPattern, String className) throws IOException {
    String jarFilename;

    String shimDirName = System.getProperty(SHIM_JAR_DIR_PROPERTY, ".");
    File shimDir = new File(shimDirName);
    if (!shimDir.exists()) {
        throw new IOException("No such shim directory: " + shimDirName);
    }

    String[] candidates = shimDir.list();
    if (null == candidates) {
        throw new IOException("Could not list shim directory: " + shimDirName);
    }

    for (String candidate : candidates) {
        if (candidate.matches(jarPattern)) {
            LOG.debug("Found jar matching pattern " + jarPattern + ": " + candidate);
            File jarFile = new File(shimDir, candidate);
            String jarFileName = jarFile.toString();
            ClassLoaderStack.addJarFile(jarFileName, className);
            LOG.debug("Successfully pushed classloader for jar: " + jarFileName);
            return;
        }
    }

    throw new IOException("Could not load shim jar for pattern: " + jarPattern);
}

From source file:com.photon.phresco.util.FileUtil.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();//from w  w w. ja  va 2s.  c o  m
        }

        //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

            if (!Constants.MACOSX.equals(file)) {
                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[BUFFER_SIZE];

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

From source file:edu.clemson.cs.nestbed.common.util.ZipUtils.java

private static void zipDirectory(File directory, String name, ZipOutputStream zos) throws IOException {
    // *MUST* append the trailing slash for a ZipEntry to identify an
    // entry as a directory.
    name += "/";//from  w ww  .j a  va  2 s .  c o m

    zos.putNextEntry(new ZipEntry(name));
    zos.closeEntry();

    String[] entryList = directory.list();

    for (int i = 0; i < entryList.length; ++i) {
        File f = new File(directory, entryList[i]);

        if (f.isDirectory()) {
            zipDirectory(f, name + f.getName(), zos);
        } else {
            FileInputStream fis = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(name + f.getName());
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesIn = 0;

            zos.putNextEntry(entry);

            while ((bytesIn = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesIn);
            }

            fis.close();
            zos.closeEntry();
        }
    }
}

From source file:Main.java

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

    if (src.isDirectory()) {

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

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

        for (int c = 0; c < files.length; c++) {
            //construct the src and dest file structure
            File srcFile = new File(src, files[c]);
            File destFile = new File(dest, files[c]);
            //recursive copy
            copy(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:Main.java

static public boolean copyAllAssertToCacheFolder(Context c) throws IOException {

    String[] files = c.getAssets().list("Devices");
    String filefolder = c.getFilesDir().toString();
    File devicefile = new File(filefolder + "/Devices/");
    devicefile.mkdirs();/*from w w w  . j  a va  2s.c  o m*/

    for (int i = 0; i < files.length; i++) {
        File devfile = new File(filefolder + "/Devices/" + files[i]);
        if (!devfile.exists()) {
            copyFileTo(c, "Devices/" + files[i], filefolder + "/Devices/" + files[i]);
        }
    }
    String[] filestr = devicefile.list();
    for (int i = 0; i < filestr.length; i++) {
        Log.i("file", filestr[i]);
    }

    return true;
}

From source file:at.ac.uniklu.mobile.sportal.util.Utils.java

/**
 * Recursively delete a directory and all of its content.
 * source: http://groups.google.com/group/android-developers/browse_thread/thread/e9eb0a17a3c7c768
 * @param dir//from w  ww  .j  a  v a  2  s.  c  o m
 * @return
 */
public static boolean deleteDir(File dir) {
    if (dir != null && 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 delete it 
    return dir.delete();
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * //from  w  ww  . j a  v a  2  s  . c o m
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple
    // jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            if (res.getProtocol().equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {

                    if (e.getName().startsWith(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:Main.java

private static void addFileToZip(String sourceFolderPath, String sourceFilePath, String baseFolderPath,
        ZipOutputStream zos) throws Exception {

    File item = new File(sourceFilePath);
    if (item == null || !item.exists())
        return; //skip if the file is not exist
    if (isSymLink(item))
        return; // do nothing to symbolic links.

    if (baseFolderPath == null)
        baseFolderPath = "";

    if (item.isDirectory()) {
        for (String subItem : item.list()) {
            addFileToZip(sourceFolderPath + File.separator + item.getName(),
                    sourceFilePath + File.separator + subItem, baseFolderPath, zos);
        }// w  w  w .j a  v  a 2 s  .c  o m
    } else {
        byte[] buf = new byte[102400]; //100k buffer
        int len;
        FileInputStream inStream = new FileInputStream(sourceFilePath);
        if (baseFolderPath.equals("")) //sourceFiles in absolute path, zip the file with absolute path
            zos.putNextEntry(new ZipEntry(sourceFilePath));
        else {//relative path
            String relativePath = sourceFilePath.substring(baseFolderPath.length());
            zos.putNextEntry(new ZipEntry(relativePath));
        }

        while ((len = inStream.read(buf)) > 0) {
            zos.write(buf, 0, len);
        }

    }
}

From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java

/**
 * @param tables//w ww.  ja va2  s .  c o  m
 */
public static String reloadHiveTable(String tables) {
    // Rewrite the table string
    String[] tokens = StringUtils.split(tables, ",");
    StringBuffer buff = new StringBuffer();
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i].trim();
        if (StringUtils.isNotEmpty(token)) {
            buff.append(";");
            buff.append("show table extended like " + token);
        }
    }
    String hiveCommand = buff.toString();
    if (StringUtils.isEmpty(hiveCommand)) {
        throw new IllegalArgumentException("The required tabes is empty");
    }
    // Call shell to generate source tabe
    String tableMetaDir = "";
    try {
        tableMetaDir = callGenerateCommand(hiveCommand);
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Failed to get metadata from upstream, for tables " + tables, e);
    }
    // Update Metadata
    if (StringUtils.isEmpty(tableMetaDir)) {
        throw new IllegalArgumentException("Failed to get metadata from upstream, for tables " + tables);
    }
    File dir = new File(tableMetaDir);
    if (!dir.exists() || !dir.isDirectory() || dir.list().length == 0) {
        throw new IllegalArgumentException("Nothing found from path " + tableMetaDir);
    }

    copyToMetaTable(tableMetaDir);

    return tableMetaDir;
}

From source file:io.druid.data.input.impl.prefetch.PrefetchableTextFilesFirehoseFactoryTest.java

private static void assertNumRemainingCacheFiles(File firehoseTmpDir, int expectedNumFiles) {
    final String[] files = firehoseTmpDir.list();
    Assert.assertNotNull(files);/*from w w  w  .  ja v  a2 s .  c  o  m*/
    Assert.assertEquals(expectedNumFiles, files.length);
}