从指定的文件、文件夹中导入图片到默认的路径

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.model;

import cn.feelingsoft.photomgr.util.ImageImport;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
*
* @author Administrator
*/
public class ImageImportTest {

private ApplicationContext context = null;
private ImageImport imageImport = null;

@Before
public void initContext() {
context = new ClassPathXmlApplicationContext("beans.xml");
imageImport = context.getBean(ImageImport.class);

}

@Test
public void imageImportTest() {

File[] rootPaths = {new File("H:/TDDOWNLOAD")};
imageImport.importImages(rootPaths);

}
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.util;

import cn.feelingsoft.photomgr.i.ImportNewFileListener;
import cn.feelingsoft.photomgr.model.ImportNewFileEvent;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.springframework.stereotype.Component;

/**
*
* @author Sanwu
*/
@Component
public class ImageImport {

// 导入新文件的监听者列表
private List<ImportNewFileListener> importNewFileListeners =
Collections.synchronizedList(new ArrayList<ImportNewFileListener>());
// 图片过滤器。用于指定的检索文件夹
private ImageFileFilter imageFileFilter;
private String checkCodeType = FileUtil.CHECK_CODE_MD5;
private Config config;

public Config getConfig() {
return config;
}

public void setConfig(Config config) {
this.config = config;
}

public String getCheckCodeType() {
return checkCodeType;
}

public void setCheckCodeType(String checkCodeType) {
this.checkCodeType = checkCodeType;
}

public ImageImport() {
}

/**
* 搜索指定的路径,返回所有文件的文件名列表
* @param rootPath 搜索的路径的根
* @return 检索到的文件的绝对路径的列表
*/
private ArrayList<String> searchPaths(File[] rootPaths) {
ArrayList<String> allSearchedFiles = new ArrayList<String>();

for (File rootPath : rootPaths) {
searchPath(allSearchedFiles, rootPath);
}
return allSearchedFiles;
}

/**
* 导入指定的文件和文件夹
* @param rootPaths 源文件、文件夹
* @param destPath 目的文件夹路径
*/
public void importImages(File[] rootPaths) {
String destPath = config.getAbstractPath(Config.TEMP_RELATIVE_PATH);
copyAndCheckFiles(searchPaths(rootPaths), destPath, prepareMessageDigest());
}

/**
* 使用指定的文件过滤器,递归搜索指定的路径,装入指定的列表
* @param filenames
* @param rootPath
* @param file
*/
private void searchPath(ArrayList<String> filenames, File file) {
if (file.isDirectory()) {
File[] subPathFiles = file.listFiles(imageFileFilter);
if (null == subPathFiles) {
return;
}
for (File subPathFile : subPathFiles) {
searchPath(filenames, subPathFile);
}
} else if (imageFileFilter.accept(file)) {
filenames.add(file.getAbsolutePath());
}
}

private ImportNewFileEvent getImportNewFileEvent(
String srcFilename, String checkCode, String destFilename) {
ImportNewFileEvent importNewFileEvent = new ImportNewFileEvent();
importNewFileEvent.setAbstractSourceFilename(srcFilename);
importNewFileEvent.setCheckCode(checkCode);
importNewFileEvent.setImportedTime(new Date(
System.currentTimeMillis()));
importNewFileEvent.setImageFilename(destFilename);
return importNewFileEvent;
}

private void copyAndCheckFiles(ArrayList<String> files, String destPath, MessageDigest messageDigest) {
FileUtil.preparePath(destPath);

for (String srcFilename : files) {
File srcFile = new File(srcFilename);
File destFile = new File(destPath + File.separator + srcFile.getName());
String checkCode = FileUtil.copyAndCheckFile(srcFile, destFile, messageDigest);
File newImageFile = FileUtil.prepareNewImageFile(destFile, checkCode);

destFile.renameTo(newImageFile);
fireImportNewFileEvent(getImportNewFileEvent(srcFilename, checkCode, destFile.getName()));
}
}

private MessageDigest prepareMessageDigest() {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance(checkCodeType);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ImageImport.class.getName()).log(Level.SEVERE, null, ex);
}
return messageDigest;
}

public JFileChooser getJPEGChooser() {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filenameFilter = new FileNameExtensionFilter(
"所有支持的图片文件",
imageFileFilter.getImageExtensions());
chooser.setFileFilter(filenameFilter);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);

return chooser;
}

private void fireImportNewFileEvent(ImportNewFileEvent importNewFileEvent) {
for (ImportNewFileListener listener : importNewFileListeners) {
listener.processImportNewFileEvent(importNewFileEvent);
}
}

public void addImportNewFileListener(ImportNewFileListener listener) {
if (null != listener) {
importNewFileListeners.add(listener);
}
}

public void removeImportNewFileListener(ImportNewFileListener listener) {
if (null != listener) {
importNewFileListeners.remove(listener);
}
}

public ImageFileFilter getImageFileFilter() {
return imageFileFilter;
}

public void setImageFileFilter(ImageFileFilter imageFileFilter) {
this.imageFileFilter = imageFileFilter;
}
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Sanwu
*/
public class FileUtil {

// 文件或文件夹路径:相对或绝对
public final static int ABSOLUTEPATH = 1;
public final static int RELATIVEPATH = 2;
//
public final static char[] hexChar = {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'};
// 文件检验码的算法
public final static String CHECK_CODE_MD5 = "MD5";
public final static String CHECK_CODE_SHA1 = "SHA1";

/**
* 截取文件的扩展名
* @param filename
* @return
*/
public static String getFileExtension(String filename) {
String extension = null;
int position = filename.lastIndexOf('.');
if (position > 0 && position < filename.length()) {
extension = filename.substring(position + 1);
}
return extension;
}

public static String getFileCheckCode(File file) {
return getFileCheckCode(file, FileUtil.CHECK_CODE_MD5);
}

/**
* 计算MD5编码
* @param file
* @return
*/
public static String getFileCheckCode(File file, String checkCodeType) {
try {
MessageDigest md5 = MessageDigest.getInstance(checkCodeType);
byte[] buffer = new byte[10 * 1024];
int readCount = 0;

FileInputStream fis = new FileInputStream(file);
while ((readCount = fis.read(buffer)) > 0) {
md5.update(buffer, 0, readCount);
}
fis.close();
return toHexString(md5.digest());
} catch (FileNotFoundException ex) {
Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null,
ex);
} catch (IOException ex) {
Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null,
ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null,
ex);
}
return null;
}

public static String toHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);
}
return sb.toString();
}

public static String getAppenedCheckCodeImageName(String oldName, String insertStr) {
String newName = null;
char concatChar = '$';

if (null == oldName || oldName.trim().equals("")) {
return null;
}
if (null == insertStr || insertStr.trim().equals("")) {
return oldName;
}
insertStr = insertStr.trim();
int position = oldName.lastIndexOf('.');
if (position < 0) {
newName = oldName + concatChar + insertStr;
} else {
newName = oldName.substring(0, position) + concatChar + insertStr + oldName.substring(position);
}
return newName;
}

public static void preparePath(File path) {
if (null != path) {
if (path.isFile()) {
String newFilename = getAppenedCheckCodeImageName(
path.getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
File dest = new File(newFilename);
path.renameTo(dest);
} else {
path.mkdirs();
}
}
}

public static void prepareFile(File file) {
if (!file.getParentFile().exists()) {
FileUtil.preparePath(file.getParentFile());
} else if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Config.SOFTWARE_NAME).log(Level.SEVERE, null, ex);
}
}
}

public static void preparePath(String pathname) {
preparePath(new File(pathname));
}

public static void prepareFile(String filename) {
prepareFile(new File(filename));
}

public static String getRelativePath(String rootPath, String absolutePath) {
if (null == rootPath
|| null == absolutePath
|| rootPath.trim().equals("")
|| absolutePath.trim().equals("")) {
return null;
}

//统一表示格式
rootPath = new File(rootPath).getPath();
absolutePath = new File(absolutePath).getAbsolutePath();

if (absolutePath.startsWith(rootPath)) {
return absolutePath.substring(rootPath.length());
}

return null;
}

public static void closeInputStream(InputStream inputStream) {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(Config.SOFTWARE_NAME).log(Level.SEVERE, null, ex);
}
}
}

public static void closeOututStream(OutputStream outputStream) {
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(Config.SOFTWARE_NAME).log(Level.SEVERE, null, ex);
}
}
}

/**
* 复制并生成文件校验码
* @param src
* @param dest
* @param checkCodeType
* @return
*/
public static String copyAndCheckFile(File src, File dest, MessageDigest messageDigest) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String toReturn = null;
byte[] buffer = new byte[10 * 1024];

try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
int readCount = 0;
while ((readCount = bis.read(buffer)) > 0) {
messageDigest.update(buffer, 0, readCount);
bos.write(buffer, 0, readCount);
}
toReturn = FileUtil.toHexString(messageDigest.digest());
} catch (FileNotFoundException ex) {
Logger.getLogger(Config.SOFTWARE_NAME).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Config.SOFTWARE_NAME).log(Level.SEVERE, null, ex);
} finally {
FileUtil.closeInputStream(bis);
FileUtil.closeOututStream(bos);
}
return toReturn;
}

public static File prepareNewImageFile(File destFile, String checkCode) {
String newImageFileName = FileUtil.getAppenedCheckCodeImageName(
destFile.getAbsolutePath(), checkCode);
File newImageFile = new File(newImageFileName);
if (newImageFile.exists()) {
newImageFile.delete();
}
return newImageFile;
}
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.util;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import org.springframework.stereotype.Component;

/**
*
* @author Langzai
*/
@Component
public class ImageFileFilter implements FileFilter {

private String[] imageExtensions = {"JPG", "JPEG", "GIF", "TIF", "TIFF", "PNG"};

public ImageFileFilter() {
sort(imageExtensions);
}

public ImageFileFilter(String[] imageExtensions) {
this.sort(imageExtensions);
this.imageExtensions = imageExtensions;
}

@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
String extension = FileUtil.getFileExtension(pathname.getName());
if (null == extension) {
return false;
} else if (imageExtensions == null) {
return true;
} else if (Arrays.binarySearch(imageExtensions, extension.
toUpperCase()) >= 0) {
return true;
}
}
return false;
}

public String[] getImageExtensions() {
return imageExtensions;
}

public void setImageExtensions(String[] imageExtensions) {
sort(imageExtensions);
this.imageExtensions = imageExtensions;
}


private void sort(String[] imageExtensions) {
Arrays.sort(imageExtensions);
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值