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.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String getDocList() {
    File docDir = new File(SpModel.getDocDir());
    String[] fileList = docDir.list();
    List<String> docName = new ArrayList<String>();
    try {// www .  j a va 2 s  .  c  om
        for (String name : fileList) {
            if (name.toLowerCase().endsWith(".xml") || name.toLowerCase().endsWith(".pdf")) {
                docName.add(name);
            }
        }
    } catch (Exception ex) {
    }
    return gson.toJson(docName);
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.SaveModelUtils.java

private static void copyToTargetLocation(File source, File destination) throws IOException {

    if (source.isDirectory()) {
        if (!destination.exists()) {
            destination.mkdir();//from  w  w w  . jav a2 s  .co  m
        }

        for (String file : source.list()) {
            File src = new File(source, file);
            File dest = new File(destination, file);
            copyToTargetLocation(src, dest);
        }

    } else {
        copySingleFile(source, destination);
    }
}

From source file:com.lovejoy777sarootool.rootool.preview.IconPreview.java

private static void loadFromRes(final File file, final ImageView icon) {
    Drawable mimeIcon = null;// w  ww . j ava2s.c o  m

    if (file != null && file.isDirectory()) {
        String[] files = file.list();
        if (file.canRead() && files != null && files.length > 0)
            mimeIcon = mResources.getDrawable(R.drawable.type_folder);
        else
            mimeIcon = mResources.getDrawable(R.drawable.type_folder_empty);
    } else if (file != null && file.isFile()) {
        final String fileExt = FilenameUtils.getExtension(file.getName());
        mimeIcon = mMimeTypeIconCache.get(fileExt);

        if (mimeIcon == null) {
            final int mimeIconId = MimeTypes.getIconForExt(fileExt);
            if (mimeIconId != 0) {
                mimeIcon = mResources.getDrawable(mimeIconId);
                mMimeTypeIconCache.put(fileExt, mimeIcon);
            }
        }
    }

    if (mimeIcon != null) {
        icon.setImageDrawable(mimeIcon);
    } else {
        // default icon
        icon.setImageResource(R.drawable.type_unknown);
    }
}

From source file:com.wordnik.swagger.codegen.util.FileUtil.java

public static void copyDirectory(File srcPath, File dstPath) {
    if (srcPath.isDirectory()) {
        if (!dstPath.exists()) {
            dstPath.mkdir();//from w ww.j av  a  2 s . c om
        }

        String files[] = srcPath.list();
        for (int i = 0; i < files.length; i++) {
            copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
        }
    } else {
        if (!srcPath.exists()) {
            throw new CodeGenerationException("Source folder does not exist");
        } else {
            try {
                InputStream in = new FileInputStream(srcPath);
                OutputStream out = new FileOutputStream(dstPath);

                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new CodeGenerationException("Copy directory operation failed");
            }
        }
    }
}

From source file:Main.java

/**
 * Gets the directory files list.//from w  ww  . ja  v a  2 s  .c om
 * 
 * @param directory
 *            the directory
 * @return the directory files list
 */
public static HashMap<String, File> getDirectoryFilesList(File directory) {

    final HashMap<String, File> directoryList = new HashMap<String, File>();

    if (directory == null) {
        return directoryList;
    }
    if (!directory.exists()) {
        return directoryList;
    }
    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()) {
                    String name = entry.getName();
                    if (name.length() > 0 && name.contains(".")) {
                        name = (String) name.subSequence(0, name.lastIndexOf('.'));
                        directoryList.put(name, entry);
                    }
                }
            }
        }
    }
    return directoryList;
}

From source file:org.callimachusproject.test.TemporaryServerFactory.java

private static File findCallimachusWebappCar() {
    File dist = new File("dist");
    if (dist.list() != null) {
        for (String file : dist.list()) {
            if (file.startsWith("callimachus-webapp") && file.endsWith(".car"))
                return new File(dist, file);
        }//from ww w  .j  a v a2s. c  o  m
    }
    File car = SystemProperties.getWebappCarFile();
    if (car != null && car.exists())
        return car;
    throw new AssertionError("Could not find callimachus-webapp.car in " + dist.getAbsolutePath());
}

From source file:ai.susi.json.JsonRepository.java

private static SortedSet<File> getDumps(final File path, final String prefix, final String suffix, int count) {
    String[] list = path.list();
    TreeSet<File> dumps = new TreeSet<File>(); // sort the names with a tree set
    for (String s : list) {
        if ((prefix == null || s.startsWith(prefix)) && (suffix == null || s.endsWith(suffix)))
            dumps.add(new File(path, s));
    }//from   ww  w.j a  v a 2  s. c  o  m
    return tailSet(dumps, count);
}

From source file:Main.java

/**
 * Indexes the given file using the given writer, or if a directory is given,
 * recurses over files and directories found under the given directory.
 * //  www  . j a  va  2s . c  o  m
 * NOTE: This method indexes one document per input file.  This is slow.  For good
 * throughput, put multiple documents into your input file(s).  An example of this is
 * in the benchmark module, which can create "line doc" files, one document per line,
 * using the
 * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
 * >WriteLineDocTask</a>.
 *  
 * @param writer Writer to the index where the given file/dir info will be stored
 * @param file The file to index, or the directory to recurse into to find files to index
 * @throws IOException If there is a low-level I/O error
 */
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 (int i = 0; i < files.length; i++) {
                    indexDocs(writer, new File(file, files[i]));
                }
            }
        } else {

            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException fnfe) {
                // 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
                return;
            }

            try {

                // make a new, empty document
                Document doc = new Document();

                // Add the path of the file as a field named "path".  Use a
                // field that is indexed (i.e. searchable), but don't tokenize 
                // the field into separate words and don't index term frequency
                // or positional information:
                Field pathField = new StringField("path", file.getPath(), Field.Store.YES);
                doc.add(pathField);

                // Add the last modified date of the file a field named "modified".
                // Use a LongField that is indexed (i.e. efficiently filterable with
                // NumericRangeFilter).  This indexes to milli-second resolution, which
                // is often too fine.  You could instead create a number based on
                // year/month/day/hour/minutes/seconds, down the resolution you require.
                // For example the long value 2011021714 would mean
                // February 17, 2011, 2-3 PM.
                doc.add(new LongField("modified", file.lastModified(), Field.Store.NO));

                // Add the contents of the file to a field named "contents".  Specify a Reader,
                // so that the text of the file is tokenized and indexed, but not stored.
                // Note that FileReader expects the file to be in UTF-8 encoding.
                // If that's not the case searching for special characters will fail.
                doc.add(new TextField("contents",
                        new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8))));

                if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
                    // New index, so we just add the document (no old document can be there):
                    System.out.println("adding " + file);
                    writer.addDocument(doc);
                } else {
                    // Existing index (an old copy of this document may have been indexed) so 
                    // we use updateDocument instead to replace the old one matching the exact 
                    // path, if present:
                    System.out.println("updating " + file);
                    writer.updateDocument(new Term("path", file.getPath()), doc);
                }

            } finally {
                fis.close();
            }
        }
    }
}

From source file:com.alibaba.jstorm.utils.JStormServerUtils.java

public static void createPid(String dir) throws Exception {
    File file = new File(dir);

    if (file.exists() == false) {
        file.mkdirs();/*from  w w w  . j  a  va2 s  .  co m*/
    } else if (file.isDirectory() == false) {
        throw new RuntimeException("pid dir:" + dir + " isn't directory");
    }

    String[] existPids = file.list();

    // touch pid before
    String pid = JStormUtils.process_pid();
    String pidPath = dir + File.separator + pid;
    PathUtils.touch(pidPath);
    LOG.info("Successfully touch pid  " + pidPath);

    for (String existPid : existPids) {
        try {
            JStormUtils.kill(Integer.valueOf(existPid));
            PathUtils.rmpath(dir + File.separator + existPid);
        } catch (Exception e) {
            LOG.warn(e.getMessage(), e);
        }
    }

}

From source file:cn.fql.utility.FileUtility.java

/**
 * Copy source folder's content to a new folder, if there are existed duplicated files and overwrite
 * flag is true, it might overwrite it/*w  ww . j a  v  a2 s.c  o  m*/
 *
 * @param sourceFolder   source folder path
 * @param newFolder      new folder path
 * @param forceOverwrite determine whether it is required to overwrite for duplicated files
 */
public static void copyFolder(String sourceFolder, String newFolder, boolean forceOverwrite) {
    String oldPath = StringUtils.replace(sourceFolder, "/", File.separator);
    String newPath = StringUtils.replace(newFolder, "/", File.separator);
    if (!oldPath.endsWith(File.separator)) {
        oldPath = oldPath + File.separator;
    }
    if (!newPath.endsWith(File.separator)) {
        newPath = newPath + File.separator;
    }
    new File(newPath).mkdirs();
    File sourceDir = new File(oldPath);
    String[] files = sourceDir.list();
    File oldFile;
    File newFile;
    for (int i = 0; i < files.length; i++) {
        oldFile = new File(oldPath + files[i]);
        newFile = new File(newPath + files[i]);
        if (oldFile.isFile() && (!forceOverwrite || (!newFile.exists() || oldFile.length() != newFile.length()
                || oldFile.lastModified() > newFile.lastModified()))) {
            copyFile(oldFile.getPath(), newFile.getPath());
        }
        if (oldFile.isDirectory()) {
            copyFolder(oldPath + files[i], newPath + files[i], forceOverwrite);
        }
    }
}