提示:仅供参考,不喜勿喷
前言
例如:事情是这样的,我在某壁纸网站抓取了一大堆的壁纸,但是抓取下来的壁纸的比例不是很搭我的电脑,所以我就想用我微薄的知识来删除那些我不想要的图片,以及重命名
一、遍历文件中的所有图片
遍历文件夹中的所有文件(我的文件夹里面全是图片),这里尝试跑一下看能不能找到这些图片,并打印出来。我的文件夹内容如下:
String str = "D:\\wallpapers\\hot";
int count=0;
File f = new File(str);
File[] files = f.listFiles();
for (File file : files) {
System.out.println(file.getName());
++count;
}
System.out.println("总共"+count+"张图片");
}
运行结果如下:
二、重命名图片的名字
遍历完成之后,只需要加上对应的操作即可;重命名代码如下
file.renameTo(new File(new_str)
最终效果为:
总结
对于删除不想要的图片,这里省略,因为我已经删除完了。当然思路和重命名差不多,以下是删除我不想要图片的代码
Tips:这里的删除不会进入回收站,直接删除
String str = "D:\\wallpapers\\hot";//访问文件夹路径
File f = new File(str);
int count = 0;
File[] files = f.listFiles();
for (File file : files) {
FileInputStream fileInputStream = new FileInputStream(file);
BufferedImage bufferedImage = ImageIO.read(fileInputStream);
fileInputStream.close();
//宽度
int width = bufferedImage.getWidth();
//高度
int height = bufferedImage.getHeight();
float width_height = (float) width / (float) height;//宽度比高度
if (width_height > 2) {
System.gc();
if (file.delete()) System.out.println(++count);
else System.out.println("删除失败");
}
只需要注意删除的时候,要把输入流关闭,以及调用一下gc就可以了。
重命名的代码如下:
String str = "D:\\wallpapers\\hot";//访问文件夹路径
File f = new File(str);
int count = 0;
int count1=0;
File[] files = f.listFiles();
for (File file : files) {
String new_str=str;
int lengths=file.getName().length();
new_str+="\\"+(++count)+file.getName().substring(lengths-4);
//拼接需要重命名的字符串,注意file.getName().substring(lengths-4)为保留原有格式:例.jpg
if(file.renameTo(new File(new_str))) ++count1;
else System.out.println("重命名失败");
System.gc();
}
System.out.println("重命名成功数量:"+(count1)+" 重命名失败数量:"+(count-count1));
ok,这就个人的见解,如有更好的更高效的改良方法,请不吝赐教。