從一系列的圖片文件夾中隨機抽取圖片


最近采集了15萬張圖片,每天采集的圖片存儲在一個新的目錄下,在測試時需要從所有文件夾中隨機抽取圖片做測試。

package com.vfsd.core;

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

public class RandSelectPicFromFolder {
    
    public static void main(String[] args) {
        String folderPath = "H:\\PicDir\\";
        listFilesFromFolder(folderPath);
    }
    
    public static void listFilesFromFolder(String foldName) {
        File folder1 = new File(foldName);
        File[] files1 = folder1.listFiles();
        for(File indexFile:files1) {
            if(indexFile.isDirectory()) {
                System.out.println("folder:"+indexFile.getName());
                selectPicFromFolder(indexFile.getAbsolutePath());
            }
            
            //if(indexFile.isFile()) {
            //    System.out.println("file:"+indexFile.getName());
            //    //
            //}
        }
    }
    
    public static void selectPicFromFolder(String folderPath) {
        File folder1 = new File(folderPath);
        File[] files1 = folder1.listFiles();
        
        int picNum = files1.length;
        
        int selectPicIndex = (int) (Math.random()*picNum);
        
        System.out.println(selectPicIndex);
        
        File selectFile = files1[selectPicIndex];
        //System.out.println("file:"+selectFile.getName());
        
        String oriFileName = selectFile.getAbsolutePath();
        String newFileName = "H:\\select_pic\\"+selectFile.getName();
        
        System.out.println(oriFileName+"  "+newFileName);
        
        try {
            copyFile(oriFileName,newFileName);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void copyFile(String oriFilePath,String newFilePath) throws IOException{
        File oriFile = new File(oriFilePath);
        File newFile = new File(newFilePath);
        
        FileInputStream fis = new FileInputStream(oriFile);
        FileOutputStream fos = new FileOutputStream(newFile);
        
        byte[] bytes = new byte[1024];
        int b=0;
        while((b=fis.read(bytes))!=-1) {
            fos.write(bytes, 0, b);
        }
        
        fos.flush();
        fis.close();
        fos.close();
        
        
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM