起由
因为规范要求,需要对一批文件重命名并获取尺寸,刚好上午的java课学了文件输入输出流,学以致用嘛,就利用java做了尝试。
功能
1.文件按照指定格式重命名;
2.文件夹内所有文件名与图片尺寸按格式写入一个TXT文件。
效果
之前:
之后:
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import java.io.*; import java.awt.image.BufferedImage; import javax.imageio.*; public class FileNameChange{ public static void main(String[] args){ String dir = "D:/filenamechangejava/"; File f1 = new File(dir+"photo"); File[] s = f1.listFiles(); String[] k = new String[100]; for(int i = 0;i < s.length;i++){ k[i] = s[i].getName(); } for(int i = 0;i < s.length;i++){ k[i] = k[i].substring(0,4)+k[i].substring(5,7)+k[i].substring(8,10)+k[i].substring(11,15)+".jpg"; s[i].renameTo(new File(dir+"photo/"+k[i])); } System.out.println("Rename complete!"); File[] s2 = f1.listFiles(); try{ for(int j = 0;j < s.length;j++){ k[j] = "\""+k[j].substring(0,12)+"\",\n"; BufferedImage pic = ImageIO.read(new FileInputStream(s2[j])); String m = k[j] + "\"" + pic.getWidth()+ "x" + pic.getHeight()+"\",\n\n"; RandomAccessFile fos = new RandomAccessFile(dir+"name.txt","rw"); long len = fos.length(); fos.seek(len); fos.writeBytes(m); fos.close(); } }catch(IOException e){ e.printStackTrace(); } System.out.println("Write name and size in \""+dir+"name.txt\" complete!"); } }
|