如何根据号码安排和重命名文件?(How to arrange and rename files according to number?)

编程入门 行业动态 更新时间:2024-10-10 12:24:26
如何根据号码安排和重命名文件?(How to arrange and rename files according to number?)

我想先排列文件,然后根据文件名中的数字指定的顺序重命名。

例如:

我有一个包含一堆不同文件的文件夹。 文件名由末尾的数字表示。 假设我们在该文件夹中有以下文件:

file_1.xml // Remains unchanged file_2.xml // Remains unchanged file_4.xml // Should be renamed to "file_3.xml" file_9.xml // Should be renamed to "file_4.xml" file_12.xml // Should be renamed to "file_5.xml"

我怎么做? 我想创建一个可靠的干净方法,按顺序重命名文件。

至今:

private void updateFilesName() { for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml"); if (!file1.exists() && file2.exists()) { file2.renameTo(file1); } } }

但这只适用于2个文件位置之间的差异为1.(如file_2和file_4之间)此方法不适用于file_9和file_12 。

I want to arrange files first and rename them according to their order that is specified by a number in the file name.

For example:

I have a folder that contains a bunch of different files. The file names are indicated by a number at the end of it. Let's say we have the following files in that folder:

file_1.xml // Remains unchanged file_2.xml // Remains unchanged file_4.xml // Should be renamed to "file_3.xml" file_9.xml // Should be renamed to "file_4.xml" file_12.xml // Should be renamed to "file_5.xml"

How do I do that? I want to create a reliable clean method that renames files in order.

So far:

private void updateFilesName() { for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml"); if (!file1.exists() && file2.exists()) { file2.renameTo(file1); } } }

But that only works if the difference between 2 file positions was 1. (like between file_2 and file_4) This method won't work for file_9 and file_12.

最满意答案

private void updateFilesName() { int j; for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); if (!file1.exists()) { j = i+1; while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) { j++; } (new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1); } } } private void updateFilesName() { int j; for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); if (!file1.exists()) { j = i+1; while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) { j++; } (new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1); } } }

更多推荐

本文发布于:2023-07-06 07:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047315.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重命名   号码   文件   arrange   files

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!