如何根据限制列出文件系统中的文件:java

时间:2014-11-03 10:47:19

标签: java file file-handling

如何使用起始编号和结束编号列出文件系统中可用的文件?

就像500中有C:\Test\个文件一样,如何列出从1到20开始的文件,如

根据此列表给出start number and end number可用于特定文件路径的文件。

我在java中尝试这个

我试过这样的事情,它给了我给定路径的所有可用文件

public static List<String> loadAllFiles(String filesLocation) {

        //find OS
        //String osName = System.getProperty("os.name");

        //replace file path based on OS
        filesLocation = filesLocation.replaceAll("\\\\|/", "\\"+System.getProperty("file.separator"));

        List<String> pdfFiles = new ArrayList<String>();
        if (log.isDebugEnabled()) {
            log.debug("In loadAllFiles execute start");
        }

        File directoryList = new File(filesLocation);
        File[] filesList = directoryList.listFiles();

        try {
            for (int count = 0; count < filesList.length; count++) {
                if (!filesList[count].isDirectory() && filesList[count].getName().endsWith(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim())) { 
                    // load only PDF  files
                    pdfFiles.add(filesList[count].getName().replace(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim(), ""));
                }
            }


        } catch (Exception filesException) {
            filesException.printStackTrace();
            //TODO : Log the exception
        } finally {

            if (filesList != null)
                filesList = null;

            if (directoryList != null)
                directoryList = null;
        }

        log.debug("In loadAllFiles execute end");

        return pdfFiles;
    }

I think the question is misunderstood, Say if i have 1000 files[file names can be anything] and i want to restrict getting the files name like i will give starting Number and ending number. like 1 to 20 and i want to load those 20 files alone. 

7 个答案:

答案 0 :(得分:8)

没有使用普通Java 7的外部库的示例

import java.io.IOException;
import java.nio.file.DirectoryStream;
import static java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

// list files starting with 1 till 20 "-.*"
public class FileNameFilter {

    private static final Filter<Path> fileNameFilter = new Filter<Path>() {
        @Override
        public boolean accept(Path entry) throws IOException {
            if (!Files.isRegularFile(entry)) {
                return false;
            }
            return entry.getFileName().toString().matches("^([1][0-9]{0,1}|2[0]{0,1})-.*");
        }
    };

    public static void main(String[] args) {
        final String filesLocation = "resources/";

        Path path = Paths.get(filesLocation);
        try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path, fileNameFilter)) {
            for (Path entry : dirStream) {
                System.out.printf("%-5s: %s%n", "entry", entry.getFileName());
            }
        } catch (IOException e) {
            // add your exception handling here
            e.printStackTrace(System.err);
        }
    }
}

修改 Java 8版本

// list files starting with 1 till 20 "-.*"
public class FileNameFilter {
    public static void main(String[] args) {
        final String filesLocation = "resources/";

        try {
            Files.walk(Paths.get(filesLocation))
                    .filter(p -> p.getFileName().toString().matches("^([1][0-9]{0,1}|2[0]{0,1})-.*"))
                    .forEach(entry -> {System.out.printf("%-5s: %s%n", "entry", entry.getFileName());});
        } catch (IOException e) {
            // add your exception handling here
            e.printStackTrace(System.err);
        }
    }
}

编辑2 列出目录中前20个文件的示例 note 文件的顺序与您在目录中运行lsdir的顺序相同。

Java 7示例

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileListLimiter {

private static final int MAX_FILES_TO_LIST = 20;

    public static void main(String[] args) {
        final String filesLocation = "resources/";

        Path path = Paths.get(filesLocation);
        try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
            int fileCounter = 1;
            for (Path entry : dirStream) {
                System.out.printf("%-5s %2d: %s%n", "entry", fileCounter++, entry.getFileName());
                if (fileCounter > MAX_FILES_TO_LIST) {
                    break;
                }
            }
        } catch (IOException e) {
            // add your exception handling here
            e.printStackTrace(System.err);
        }
    }
}

Java 8示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileListLimiter {

private static final int MAX_FILES_TO_LIST = 20;

    public static void main(String[] args) {
        final String filesLocation = "resources/";

        try {
            Files.walk(Paths.get(filesLocation))
                    .filter(p -> p.toFile().isFile())
                    .limit(MAX_FILES_TO_LIST)
                    .forEach(entry -> {System.out.printf("%-5s: %s%n", "entry", entry.getFileName());});
        } catch (IOException e) {
            // add your exception handling here
            e.printStackTrace(System.err);
        }
    }
}

答案 1 :(得分:1)

尝试类似

的内容
final String pattern = "^[1-20].*";
final FileFilter filter = new RegexFileFilter(pattern);
final File[] files = directory.listFiles(filter);

答案 2 :(得分:1)

为什么不使用这个逻辑。它很直接,你不需要任何替换或替换。我认为你将能够很容易地将它转换成代码到Java。我没有测试正则表达式,但你得到了基本的想法。

1.使用扫描仪(或任何其他方式)获取开始和结束限制的输入范围。

2.创建目录列表,扫描目录中的每个文件。在这里使用for循环。

3.定义正则表达式以仅获取文件的起始数据。

      start pattern = (^[0-9]{0,2})[a-zA-Z].+[0-9]{0,2}$ use grouping in regular expression to fetch this group1

4.如果从group1获取值,请检查文件名是否以group1数据开头。

5如果此数据介于您要搜索的范围之间,则创建一个arraylist并将匹配的文件存储在arraylist中。

6.继续进行直到目录结束。最终的arraylist将包含给定范围内的文件。

希望这会有所帮助

答案 3 :(得分:1)

从Java 7开始,您可以利用Files#walkFileTree。在visitFile期间,您可以使用正则表达式查找特定文件。

像这样的东西

Path start = Paths.get(filesLocation);

Final Pattern pattern = Pattern.compile("^([1]?[0-9]|[2][0])\\.pdf");

Files.walkFileTree(start, new SimpleFileVisitor<>()  
{  
   @Override  
   public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs)  
      throws IOException  
   { 

    File f = filePath.toFile();
    if (pattern.matcher().matches(f.getName())) {
            System.out.println("Valid match found " + f.getName())
    }  
      return FileVisitResult.CONTINUE;  
   }  
});  

答案 4 :(得分:1)

我不确定我是否完全理解您的问题,但这是一个Java 8示例,它迭代按名称排序的目录文件,从给定的偏移量开始并将结果限制为给定的大小。它还允许您从结果中包含/排除目录。

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DirectoryWalkerTest {

    public static void main(final String... args) throws IOException {
        final String filesLocation = "/path/to/files";

        System.out.println(getFiles(filesLocation, true, 0, 10));
        System.out.println(getFiles(filesLocation, true, 10, 10));

        System.out.println(getFiles(filesLocation, false, 0, 10));
        System.out.println(getFiles(filesLocation, false, 10, 10));
    }

    /**
     * Returns a limited list of filenames starting at the given offset.
     *
     * @param filesLocation     the directory to scan
     * @param filterDirectories should we include directories in results
     * @param offset            the starting offset
     * @param limit             the maximum number of results
     * @return a collection of file names
     */
    private static Collection<String> getFiles(final String filesLocation, final boolean filterDirectories,
            final int offset, final int limit) throws IOException {
        Stream<Path> stream = Files.list(Paths.get(filesLocation));

        if (filterDirectories) {
            stream = stream.filter(path -> !Files.isDirectory(path));
        }

        return stream
                .map(Path::toString)
                .sorted()
                .skip(offset)
                .limit(limit)
                .collect(Collectors.toList());
    }

}

答案 5 :(得分:1)

根据您的代码,您可以尝试:

int begin = 0;
int limit = 10;
for (int count = 0; count < filesList.length; count++)
{
    if (!filesList[count].isDirectory() && filesList[count].getName().endsWith(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim()))
    {
        // moving to begin index, only if the file is not a directory and is matching your criteria, whatever it is
        if (count < begin) continue;

        // load only PDF  files
        pdfFiles.add(filesList[count].getName().replace(SPLIT_AND_SAVE_WORKING_FILE_EXTENSION.trim(), ""));
    }

    // Stopping when limit is reached
    if (pdfFiles.size() == limit) break;
}

根据您的条件,它将移至begin索引并获取limit个项目。

答案 6 :(得分:1)

我玩弄它并提出了适合我的东西。也许你可以找到你需要的部件。如果您不想要完整路径,只需删除getCanonicalPath()。

    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.util.ArrayList;

    public class GetFirst_20_pdf_files {

        // Creating an empty array list with 10 entries (the default)
        ArrayList<String> pdfFiles = new ArrayList<String>();

        public ArrayList<String> myList() {
            // here you can get start and end from user
            int start = 2;
            int end   = 4;
            // and set the directory
            String filesLocation = ".";

            File directoryList = new File(filesLocation); 
            File[] files = directoryList.listFiles();
            int count = 0;
            for (File file : files) {
                // don't want directories
                if (file.isDirectory()) { continue; }
                // want ".pdf" files only
                if (!file.getName().toLowerCase().endsWith(".pdf")) { continue; }
                // only want between start and end
                count++;
                if (count >= start && count <= end) {
                try {
                     pdfFiles.add(file.getCanonicalPath());
                 } catch (IOException e) {
                     System.out.println(e);
                 }

                 if (count >= end) { return pdfFiles; }
                }
            }
            return pdfFiles;
        }

        public static void main(String[] args) throws IOException {

            GetFirst_20_pdf_files L = new GetFirst_20_pdf_files();
            ArrayList<String> aList = L.myList();

            for (String p : aList) {
                System.out.println(p);
            }
        }
    }