无法访问0以外的索引

时间:2017-05-18 10:23:24

标签: java arrays

我试图编写一个程序来快速重命名文件夹中的某些文件。

文件的名称如下:

C:\ Users \ user \ Documents \ Reports \ Report FirstName LastName FileNameExtension

我想像这样重命名:

C:\ Users \ user \ Documents \ Reports \ Report LastName FirstName FileNameExtension

到目前为止,这是我的代码:

public class FileRenamer {

    public static void main(String[] args) {

        List<String> filePaths = new ArrayList<String>();

        try(Stream<Path> paths = Files.walk(Paths.get(args[0]))) {
            paths.forEach(filePath -> {
                filePaths.add(filePath.toString());
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        filePaths.forEach(filePath -> {

            String[] splitPath = filePath.split(" ");
            String fileNameExtension = splitPath[2].split(".")[1];
            splitPath[2] = splitPath[2].split(".")[0];

            String newFilePath = splitPath[0] + " " + splitPath[2] + " " + 
                                 splitPath[1] + "." + fileNameExtension;

            new File(filePath).renameTo(new File(newFilePath));

        });

    }

}

我的问题是它不断为splitPath数组抛出ArrayIndexOutOfBoundsException。但是,当我运行for循环将索引从0输出到2时,它不会抛出异常。我做错了什么?

编辑:这是for-loop

for(int i = 0; i < splitPath.length; i++) {
    System.out.println(i + ": " + splitPath[i]);
}

将其输出到控制台:

0: C:\Users\user\Documents\Reports\Report
1: FirstName
2: LastName.FileNameExtension

1 个答案:

答案 0 :(得分:1)

Files.walk()不仅打印目录中的常规文件,还打印目录本身和任何隐藏文件。那些可能不适合你的模式。

Files.walk(Paths.get("/home/joost"), 1).forEach(p -> System.out.println(p.toString()));

/home/joost
/home/joost/someRegularFile.jpg
/home/joost/.profile
...

此外,Path::toString()给出了完整路径,而不仅仅是文件名。因此,如果路径中的任何目录中有空格,您将获得意外结果。