天天看點

用JAVA對檔案進行整理

由于本人經常買一些百度雲資料而商家整理的又十分雜亂,如下圖每次下載下傳下來大約500多個圖檔檔案,

用JAVA對檔案進行整理

 熟悉的同學們沒看錯,這就是得到APP裡的課程,為了圖便宜就從某寶上以低價把所有的課程都買了下來。但是把圖檔傳到手機上看很不友善,因為商家整理的并不是很好,有時候刷到下一張圖檔就跟上一張不配套了,是以我就打算把每天的課程分檔案夾整理,每個檔案夾大約有2到3個jpg檔案,整理結果如下圖:

用JAVA對檔案進行整理

實作步驟:

首先觀察檔案名,發現名稱格式為qs+日期+标題+頁數。那麼将檔案夾的名字用正規表達式提取建立為日期+标題,圖檔檔案存儲名稱依舊使用原名。

JAVA的代碼如下:

package tian.cheng.shear;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy {
	public static void main(String[] args) {
		long s = System.currentTimeMillis();
		String name = null;
		File file = new File("E:\\前哨2018\\2018年");
		String[] strArr = file.list();				
		for(String str : strArr){
			//System.out.println(str.replaceAll("[^(\\u4e00-\\u9fa5)]", "") );//過濾出文字
			//System.out.println(str);//原檔案名
			//System.out.println(str.replaceAll("[^(0-9)]", "").substring(0, 4));//提取前4個數字
			String lstr = str.replaceAll("[^(0-9)]", "").substring(0, 4)+
					str.replaceAll("[^(\\u4e00-\\u9fa5)]", "");						
			FileInputStream fis = null;
			FileOutputStream fos = null;
			File fil = new File("E:\\前哨2018\\2018\\"+lstr);//建立複制檔案夾			
			if(!fil.exists()){
	            fil.mkdir();
	        }
			if(fil.isDirectory()) {
				File fileList = new File(fil,str);				
						try {
							fileList.createNewFile();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						name = fileList.getName();
						System.out.println(fil+"\\"+name);//列印被複制檔案路徑
			}
			try{
				fis = new FileInputStream(file+"\\"+str);
				fos = new FileOutputStream(fil+"\\"+name);
				//定義位元組數組,緩沖
				byte[] bytes = new byte[1024*10];
				//讀取數組,寫入數組
				int len = 0 ; 
				while((len = fis.read(bytes))!=-1){
					fos.write(bytes, 0, len);
				}	
			}catch(IOException ex){
				System.out.println(ex);
				throw new RuntimeException("檔案複制失敗");
			}finally{
				try{
					if(fos!=null)
						fos.close();
				}catch(IOException ex){
					throw new RuntimeException("釋放資源失敗");
				}finally{
					try{
						if(fis!=null)
							fis.close();
					}catch(IOException ex){
						throw new RuntimeException("釋放資源失敗");
					}
				}
			}
		}
		long e = System.currentTimeMillis();
		System.out.println(e-s);
	}
}