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:net.ftb.util.FileUtils.java

public static void copyFolder(File sourceFolder, File destinationFolder, boolean overwrite) throws IOException {
    if (sourceFolder.isDirectory()) {
        if (!destinationFolder.exists()) {
            destinationFolder.mkdirs();//w  w w .  ja  va 2  s  .c om
        }
        String files[] = sourceFolder.list();
        for (String file : files) {
            File srcFile = new File(sourceFolder, file);
            File destFile = new File(destinationFolder, file);
            copyFolder(srcFile, destFile, overwrite);
        }
    } else {
        copyFile(sourceFolder, destinationFolder, overwrite);
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (String child : children) {
            boolean success = deleteDir(new File(dir, child));
            if (!success) {
                return false;
            }/*w  w  w. ja  v a 2  s  .  c o m*/
        }
    }

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

From source file:com.google.acre.servlet.OneTrueConfig.java

public static List<String[]> parse() throws JSONException, OneTrueConfigException {

    File cdir = new File(System.getProperty("configDir"));
    List<String[]> rules = new ArrayList<String[]>();

    String[] files = cdir.list();
    Arrays.sort(files);/*from ww  w.jav  a2  s .  c o  m*/

    for (String s : files) {
        File f = new File(cdir, s);
        String name = f.getName();
        if (name.startsWith("ots.") && name.endsWith(".conf")) {
            String contents = null;
            try {
                contents = FileUtils.readFileToString(f);
                rules.addAll(parse(contents));
            } catch (IOException e) {
                throw new OneTrueConfigException("Error reading file: " + f);
            }
        }
    }

    // this rule must be last
    String[] dispatch_rule = { "/", "DispatchServlet", null, "/" };
    rules.add(dispatch_rule);

    return rules;
}

From source file:com.nridge.core.base.std.FilUtl.java

/**
 * Compresses the input path name into a ZIP output file stream.  The
 * method will recursively process all files and sub folders within
 * the input path file./*from  w w  w  . j  a  v a2  s .c  o  m*/
 *
 * @param aPathName Identifies the name of the folder to compress.
 * @param aZipOutStream A previously opened ZIP output file stream.
 * @throws IOException Related to opening the file streams and
 * related read/write operations.
 */
static public void zipPath(String aPathName, ZipOutputStream aZipOutStream) throws IOException {
    int byteCount;
    byte[] ioBuf;
    String[] fileList;
    File zipFile, inFile;
    FileInputStream fileIn;

    zipFile = new File(aPathName);
    if (!zipFile.isDirectory())
        return;

    fileList = zipFile.list();
    if (fileList == null)
        return;

    for (String fileName : fileList) {
        inFile = new File(aPathName, fileName);
        if (inFile.isDirectory())
            zipPath(inFile.getPath(), aZipOutStream);
        else {
            ioBuf = new byte[FILE_IO_BUFFER_SIZE];
            fileIn = new FileInputStream(inFile);
            aZipOutStream.putNextEntry(new ZipEntry(inFile.getName()));
            byteCount = fileIn.read(ioBuf);
            while (byteCount > 0) {
                aZipOutStream.write(ioBuf, 0, byteCount);
                byteCount = fileIn.read(ioBuf);
            }
            fileIn.close();
        }
    }
}

From source file:org.pentaho.support.cmd.CommandLineUtility.java

/**
 * deletes the empty directory// ww w . j  a  v a  2 s.c  o m
 * 
 * @param file
 */
private static void delete(File file) {
    if (file.isDirectory()) {
        if (file.list().length == 0) {
            file.delete();
        } else {
            String files[] = file.list();
            for (String temp : files) {
                File fileDelete = new File(file, temp);
                delete(fileDelete);
            }
            if (file.list().length == 0) {
                file.delete();
            }
        }
    } else {
        file.delete();
    }
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure.
 * //w  w  w. j a v  a2  s. com
 * @param sourceDirectoryPath the directory to be uploaded
 * @param destDirName the path on ftp where directory will be uploaded
 * @param numberOfRetryCounter number of attempts to be made for uploading the directory
 * @throws FTPDataUploadException if an error occurs while uploading the file
 * @throws IOException if an error occurs while making the ftp connection
 * @throws SocketException if an error occurs while making the ftp connection
 */
public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData)
        throws FTPDataUploadException, SocketException, IOException {
    boolean isValid = true;
    if (ftpInformation.getSourceDirectoryPath() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DIR);
        throw new FTPDataUploadException(VAR_SOURCE_DIR);
    }
    if (ftpInformation.getDestDirName() == null) {
        isValid = false;
        LOGGER.error(VAR_SOURCE_DES);
        throw new FTPDataUploadException(VAR_SOURCE_DES);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String destDirName = ftpInformation.getDestDirName();
        String destinationDirectory = ftpInformation.getUploadBaseDir();
        if (destDirName != null && !destDirName.isEmpty()) {
            String uploadBaseDir = ftpInformation.getUploadBaseDir();
            if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) {
                destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        destDirName);
            } else {
                destinationDirectory = destDirName;
            }

        }
        FileInputStream fis = null;
        try {
            createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(),
                    ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut());

            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Upload...");
            } else {
                LOGGER.info("Invalid Connection to FTP server. Disconnecting Client");
                client.disconnect();
                isValid = false;
                throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client");
            }
            if (isValid) {

                // code changed for keeping the control connection busy.
                client.setControlKeepAliveTimeout(300);
                client.setFileType(FTP.BINARY_FILE_TYPE);
                createFtpDirectoryTree(client, destinationDirectory);
                // client.makeDirectory(destinationDirectory);
                if (deleteExistingFTPData) {
                    deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData);
                }
                File file = new File(ftpInformation.getSourceDirectoryPath());
                if (file.isDirectory()) {
                    String[] fileList = file.list();
                    for (String fileName : fileList) {
                        String inputFile = EphesoftStringUtil
                                .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName);
                        File checkFile = new File(inputFile);
                        if (checkFile.isFile()) {
                            LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName));
                            fis = new FileInputStream(inputFile);
                            try {
                                client.storeFile(fileName, fis);
                            } catch (IOException e) {
                                int retryCounter = ftpInformation.getNumberOfRetryCounter();
                                LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-",
                                        (retryCounter + 1)));
                                if (retryCounter < ftpInformation.getNumberOfRetries()) {
                                    retryCounter = retryCounter + 1;
                                    uploadDirectory(ftpInformation, deleteExistingFTPData);
                                } else {
                                    LOGGER.error("Error in uploading the file to FTP server");
                                }
                            } finally {
                                try {
                                    if (fis != null) {
                                        fis.close();
                                    }
                                } catch (IOException e) {
                                    LOGGER.info(EphesoftStringUtil
                                            .concatenate("Could not close stream for file.", inputFile));
                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("File does not exist..");
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Disconnecting from FTP server....", e);
            }
        }
    }
}

From source file:com.emental.mindraider.core.search.SearchCommander.java

/**
 * Index documents.//from   ww w  .  j  a  v  a2  s  .  com
 * 
 * @param writer
 *            the index writer
 * @param file
 *            the file to write
 * @param rebuildSearchIndexJDialog
 *            the rebuild search index JDialog
 * @throws IOException
 *             the I/O exception
 */
public static void indexDocs(IndexWriter writer, File file) throws IOException {
    // do not try to index files that cannot be read
    if (file.canRead()) {
        if (file.isDirectory()) {
            String[] files = file.list();
            // an IO error could occur
            if (files != null) {
                for (String filename : files) {
                    indexDocs(writer, new File(file, filename));
                }
            }
        } else {
            StatusBar.setText(action, file.getAbsolutePath(), 70);

            try {
                // I'm interested only in indexing of concepts
                if (file.getAbsolutePath()
                        .indexOf(File.separator + CONCEPTS_DIRECTORY_NAME + File.separator) >= 0) {
                    ConceptResource conceptResource = new ConceptResource(new Resource(file.getAbsolutePath()));

                    // FTS index
                    // TODO parse notebook label from the path for now
                    String notebookUri = conceptResource.getNotebookUri();
                    String notebookLabel;
                    if (notebookUri != null && (notebookUri.indexOf("#") >= 0)) {
                        // TODO from time to time the last letter is killed
                        notebookLabel = notebookUri.substring(notebookUri.indexOf("#") + 1,
                                notebookUri.length());
                        // TODO ugly hack - label must be loaded from the model (slow)
                        notebookLabel = notebookLabel.replaceAll("_", " ");
                    } else {
                        notebookLabel = "Notebook";
                    }

                    // tag (infiltrated)
                    CategoryProperty[] tagsAndFlag = conceptResource.getCategories();
                    if (tagsAndFlag != null && tagsAndFlag.length > 0) {
                        for (CategoryProperty tagOrFlag : tagsAndFlag) {
                            // only tags (not the flag!) are indexed
                            if (tagOrFlag.getCategoryValue() != null
                                    && tagOrFlag.getCategoryValue().length() > 0) {
                                if (!tagOrFlag.getCategoryValue()
                                        .startsWith(MindRaiderConstants.MR_OWL_FLAG_NS)) {
                                    MindRaider.tagCustodian.addOrInc(
                                            new TagEntryImpl(tagOrFlag.getCategoryValue(),
                                                    tagOrFlag.getCategoryCaption(), 1),
                                            new TaggedResourceEntry(notebookUri, notebookLabel,
                                                    conceptResource.getUri(), conceptResource.getLabel(),
                                                    conceptResource.resource.getMetadata().getTimestamp(),
                                                    file.getAbsoluteFile().getAbsolutePath()));
                                }
                            }
                        }
                    }

                    // write it to index
                    writer.addDocument(FileDocument.Document(file, notebookLabel, conceptResource.getLabel(),
                            conceptResource.getUri()));
                }
            } catch (EOFException e) {
                logger.debug("Unable to read file " + file.getAbsolutePath(), e);
            }
            // at least on windows, some temporary files raise this
            // exception with an "access denied" message
            // checking if the file can be read doesn't help
            catch (Exception e) {
                logger.debug("File not found!", e);
            }
        }
    }
}

From source file:FileUtils.java

/**
 * Utility method for copying directory//w  w  w  . jav a  2 s .com
 * @param srcDir - source directory
 * @param dstDir - destination directory
 */
public static void copyDirectory(File srcDir, File dstDir) throws IOException {

    if (".svn".equals(srcDir.getName())) {
        return;
    }

    if (srcDir.isDirectory()) {
        if (!dstDir.exists()) {
            dstDir.mkdir();
        }

        for (String aChildren : srcDir.list()) {
            copyDirectory(new File(srcDir, aChildren), new File(dstDir, aChildren));
        }
    } else {
        copyFile(srcDir, dstDir);
    }
}

From source file:com.phonegap.DirectoryManager.java

/**
 * Delete directory.//from  w w  w  .j a v  a2 s.c om
 * 
 * @param fileName      The name of the directory to delete
 * @return            T=deleted, F=could not delete
 */
protected static boolean deleteDirectory(String fileName) {
    boolean status;
    SecurityManager checker = new SecurityManager();

    // Make sure SD card exists
    if ((testSaveLocationExists()) && (!fileName.equals(""))) {
        File path = Environment.getExternalStorageDirectory();
        File newPath = constructFilePaths(path.toString(), fileName);
        checker.checkDelete(newPath.toString());

        // If dir to delete is really a directory
        if (newPath.isDirectory()) {
            String[] listfile = newPath.list();

            // Delete all files within the specified directory and then delete the directory
            try {
                for (int i = 0; i < listfile.length; i++) {
                    File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString());
                    deletedFile.delete();
                }
                newPath.delete();
                Log.i("DirectoryManager deleteDirectory", fileName);
                status = true;
            } catch (Exception e) {
                e.printStackTrace();
                status = false;
            }
        }

        // If dir not a directory, then error
        else {
            status = false;
        }
    }

    // If no SD card 
    else {
        status = false;
    }
    return status;
}

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

/**
 * Recursively copying a folder.//from   w  w w. j a  va2s.c om
 *
 * @param src File
 * @param dest File
 * @throws IOException
 */
public static void copyFolder(File src, File dest) throws IOException {

    if (src.isDirectory()) {

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

        String files[] = src.list();
        for (String file : files)
            copyFolder(new File(src, file), new File(dest, file));

    } else {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);

        byte[] buffer = new byte[1024];

        int length;
        while ((length = in.read(buffer)) > 0)
            out.write(buffer, 0, length);

        in.close();
        out.close();
    }
}