从项目中的文件夹“files”查询文件

时间:2016-02-26 12:40:07

标签: java

我的项目中有一个文件夹“files”。我想创建一个包含所有文件的查询。 1.如何在不指定完整路径的情况下打开该文件夹? 2.如何将我的文件夹中的所有文件放到此查询中?

ArrayDeque<File> files = new ArrayDeque<File>();
我写了一些代码。但程序给我文件夹的名称,而不是文件的名称。所以我的程序在我的项目文件夹中找不到文件夹。如何在没有所有路径的情况下获取我的文件夹“folder1”?这是我的代码

public static void main(String args[])
{
    File file = new File("<folder1>");
    ArrayDeque<File> queue = new ArrayDeque<File>();
    filesQueue(file, queue);
    System.out.print(queue.getFirst());
}

public static ArrayDeque<File> filesQueue(File f,  ArrayDeque<File> queue) {
        if (f.isDirectory()) {
            for (File file : f.listFiles()) {
                filesQueue(file, queue);
            }
        } else {
            queue.addLast(f);
        }

    return queue;
}

2 个答案:

答案 0 :(得分:1)

File file=new File("<folder-name>");
ArrayDeque<File> filesQueue=listFiles(file);

static ArrayDeque<File> fileList=new ArrayDeque<File>();
public ArrayDeque<File> listFiles(File folder) {

    for (File f : folder.listFiles()) {
        if (f.isDirectory()) {
            listFiles(f);
        } else {
           fileList.add(f);
        }
    }
return fileList;
}

答案 1 :(得分:0)

#!/usr/bin/python

"""
Update hook that rejects a branch creation (but does
not reject normal update nor deletion) of a branch
whose name matches some other, existing branch.
"""

# NB: we can't actually get git to supply additional
# arguments but this lets us test things locally, in
# a repository.
import argparse
import sys
import subprocess

NULL_SHA1 = b'0' * 40

# Because we're using git we store and match the ref
# name as a byte string (this matters for Python3, but not
# for Python2).
PREFIX_TO_TYPE = {
    b'refs/heads/': 'branch',
    b'refs/tags/': 'tag',
    b'refs/remotes/': 'remote-branch',
}

def get_reftype(refname):
    """
    Convert full byte-string reference name to type; return
    the type (regular Python string) and the short name (binary
    string).  Type may be 'unknown' in which case the short name
    is the full name.
    """
    for key in PREFIX_TO_TYPE.keys():
        if refname.startswith(key):
            return PREFIX_TO_TYPE[key], refname[len(key):]
    return 'unknown', refname

class RefUpdate(object):
    """
    A reference update has a reference name and two hashes,
    old and new.
    """
    def __init__(self, refname, old, new):
        self.refname = refname
        self.reftype, self._shortref = get_reftype(refname)
        self.old = old
        self.new = new

    def __str__(self):
        return '{0}({1} [{2} {3}], {4}, {5})'.format(self.__class__.__name__,
            self.refname.decode('ascii'),
            self.reftype, self.shortref.decode('ascii'),
            self.old.decode('ascii'),
            self.new.decode('ascii'))

    @property
    def shortref(self):
        "get the short version of the ref (read-only, property fn)"
        return self._shortref

    @property
    def is_branch(self):
        return self.reftype == 'branch'

    @property
    def is_create(self):
        return self.old == NULL_SHA1

def get_existing_branches():
    """
    Use git for-each-ref to find existing ref names.
    Note that we only care about branches here, and we can
    take them in their short forms.

    Return a list of all branch names.  Note that these are
    binary strings.
    """
    proc = subprocess.Popen(['git', 'for-each-ref',
        '--format=%(refname:short)', 'refs/heads/'],
        stdout=subprocess.PIPE)
    result = proc.stdout.read().splitlines()
    status = proc.wait()
    if status != 0:
        sys.exit('help! git for-each-ref failed: exit {0}'.format(status))
    return result

def update_hook():
    parser = argparse.ArgumentParser(description=
        'git update hook that rejects branch create'
        ' for case-insensitive name collision')
    parser.add_argument('-v', '--verbose', action='store_true')
    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('ref', help=
        'full reference name for update (e.g., refs/heads/branch)')
    parser.add_argument('old_hash', help='previous hash of ref')
    parser.add_argument('new_hash', help='proposed new hash of ref')

    args = parser.parse_args()
    update = RefUpdate(args.ref.encode('utf-8'),
        args.old_hash.encode('utf-8'), args.new_hash.encode('utf-8'))

    if args.debug:
        args.verbose = True

    if args.verbose:
        print('checking update {0}'.format(update))

    # if not a branch, allow
    if not update.is_branch:
        if args.debug:
            print('not a branch; allowing')
        sys.exit(0)
    # if not a creation, allow
    if not update.is_create:
        if args.debug:
            print('not a create; allowing')
        sys.exit(0)

    # check for name collision - get existing branch names
    if args.debug:
        print('branch creation! checking existing names...')
    names = get_existing_branches()
    for name in names:
        if args.debug:
            print('check vs {0} = {1}'.format(name.decode('ascii'),
                name.lower().decode('ascii')))
        if update.shortref.lower() == name.lower():
            sys.exit('Create branch {0} denied: collides with'
                ' existing branch {1}'.format(update.shortref.decode('ascii'),
                name.decode('ascii')))

    # whew, made it, allow
    if args.verbose:
        print('all tests passed, allowing')
    return 0

if __name__ == "__main__":
    try:
        sys.exit(update_hook())
    except KeyboardInterrupt:
        sys.exit('\nInterrupted')