DirectoryStream<路径>以随意的方式列出文件 [英] DirectoryStream<Path> lists files in a haphazard manner

查看:367
本文介绍了DirectoryStream<路径>以随意的方式列出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从文件夹中检索一组JPG文件,以便我可以创建一个电影。问题是文件以随意的方式列出,因此以随意的方式处理。这是一个截图:

I have to retrieve a set of JPG files from the folder so that I can create a movie with it. The problem is that the files are listed in a haphazard manner and hence are processed in a haphazard manner. Here is a screenshot:

我需要它们作为img0,img1 ..... imgn

我如何做?

**我开发了一个自定义排序方案,但我得到一个例外。编码在这里给出:

I need them in a sequential manner as img0,img1.....imgn
How do I do that?
**I deveopled a custom sorting scheme but I get an exception. The coding is given here: "

try{
                int totalImages = 0;
                int requiredImage = 0;
                jpegFiles = Files.newDirectoryStream(Paths.get(pathToPass).getParent(), "*.JPG");
                Iterator it = jpegFiles.iterator();
                Iterator it2 = jpegFiles.iterator();
                Iterator it3 = jpegFiles.iterator();
                while(it.hasNext()){
                    it.next();
                    totalImages++;
                }
                System.out.println(totalImages);
                sortedJpegFiles = new String[totalImages];
                while(it2.hasNext()){
                    Path jpegFile = (Path)it2.next();
                    String name = jpegFile.getFileName().toString();
                    int index = name.indexOf(Integer.toString(requiredImage));
                    if(index!=-1){
                        sortedJpegFiles[requiredImage] = jpegFile.toString();
                    }
                    requiredImage++;
                }
                for(String print : sortedJpegFiles){
                    System.out.println(print);
                }

            }catch(IOException e){
                e.printStackTrace();  
            }  

异常

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Iterator already obtained
    at sun.nio.fs.WindowsDirectoryStream.iterator(Unknown Source)
    at ScreenshotDemo.SCapGUI$VideoCreator.run(SCapGUI.java:186)
    at ScreenshotDemo.SCapGUI$1.windowClosing(SCapGUI.java:30)
    at java.awt.Window.processWindowEvent(Unknown Source)
    at javax.swing.JFrame.processWindowEvent(Unknown Source)
    at java.awt.Window.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)


推荐答案

自定义比较器



您必须提取数字部分,可能使用一些正则表达式,然后使用分类。自定义 比较器 可能会为您封装自定义数值比较。

Custom Comparator

You'll have to extract the number part, possibly using some regular expression, and then use that to sort. A custom Comparator might encapsulate the custom numerical comparison for you.

import java.util.*;
import java.util.regex.*;

// Sort strings by last integer number contained in string.
class CompareByLastNumber implements Comparator<String> {
    private static Pattern re = Pattern.compile("[0-9]+");
    public boolean equals(Object obj) {
        return obj != null && obj.getClass().equals(getClass());
    }
    private int num(String s) {
        int res = -1;
        Matcher m = re.matcher(s);
        while (m.find())
            res = Integer.parseInt(m.group());
        return res;
    }
    public int compare(String a, String b) {
        return num(a) - num(b);
    }
    public static void main(String[] args) {
        Arrays.sort(args, new CompareByLastNumber());
        for (String s: args)
            System.out.println(s);
    }
}



避免 IllegalStateException



参考您的更新问题:您遇到的异常是因为您尝试迭代 DirectoryStream 多次。引用其参考


虽然 DirectoryStream extends Iterable ,它不是
通用 Iterable ,因为它只支持一个迭代器;
调用迭代器方法来获取第二个或后续迭代器
throws IllegalStateException

While DirectoryStream extends Iterable, it is not a general-purpose Iterable as it supports only a single Iterator; invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.

所以你看到的行为是预期的。您应该将所有文件收集到一个列表中。以下这些行:

So the behaviour you see is to be expected. You should collect all your files to a single list. Something along these lines:

List<Path> jpegFilesList = new ArrayList<>();
while (Path p: jpegFiles)
  jpegFilesList.add(p);
sortedJpegFiles = new String[jpegFilesList.size()];
for(Path jpegFile: jpegFilesList) {
  …
}

请注意,关于IllegalStateException的此问题与您提出的原始问题相当不同。所以在一个单独的问题中会更好。请记住,SO是不是论坛。所以请坚持每个问题一个问题。

Note that this issue about the IllegalStateException is rather distinct from the original question you asked. So it would be better off in a separate question. Remember that SO is not a forum. So please stick to one issue per question.

这篇关于DirectoryStream&LT;路径&GT;以随意的方式列出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆