文件(img、pdf等等)常用方法

0.jsp表示

<input type="hidden" value="${GPM010FormBean.campaignImagePath}" id="detImg02_resetHide"/>
<html:hidden name="GPM010FormBean" property="campaignImagePath" styleId="detImg02_clearHide"/>
<img id="detImg02" src="${GPM010FormBean.campaignImagePath }" width="80" height="80" hspace="5" border="1"/>
<html:file name="GPM010FormBean" property="campaignImage" styleId="detFile02" style="background-color: #FFF9CC;" accept="image/jpeg,image/png,image/gif"/>
<input type="button" name="bttn" class="wideBtn" onclick="clearDet('02');clearHiddenImgPath('02');" value="クリア"/>

1.文件后缀名取得

	/**
	 * 拡張子を取得する
	 *
	 * @param fileName
	 * @return ".xxx"文字列
	 */
	public static String getExt(String fileName) {


		int dotLastIndex = fileName.lastIndexOf(".");
		if (fileName == null || dotLastIndex < 0
				|| dotLastIndex == fileName.length() - 1) {
			// ファイル名がない場合、もしくは拡張子がない場合
			return null;
		}
		String ext = fileName.substring(dotLastIndex);
		return ext;
	}

2.在指定路径,找指定文件名,可以写后缀名,也可以不写。

	/**
	 * ディレクトリ先からファイル名を取得する
	 *
	 * @param directoryPath ディレクトリ先
	 * @param fileNameNoSuffix ファイル名(".pdf"文字列)
	 * @param fileNameSuffix 拡張子
	 * @return "xxx.xxx"文字列
	 */
	public static String findFileName(String directoryPath, String fileNameNoSuffix, String fileNameSuffix) {
		String fileName = "";
		if (StringUtils.isEmpty(directoryPath)) {
			return fileName;
		}
		File directory = new File(directoryPath);
		File[] files = directory.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				if (file.isFile()) {
					String fileNm = file.getName();
					if(StringUtil.required(fileNameSuffix)) {
						// 拡張が有り
						if (fileNm.equals(fileNameNoSuffix + fileNameSuffix)) {
							fileName = fileNm;
							break;
						}
					}else {
						// 拡張が無
						int indexDot = fileNm.lastIndexOf(GPMConstant.FILE_EXT_DOT);
						if (indexDot != -1) {
							if (fileNm.substring(0, indexDot).equals(fileNameNoSuffix)) {
								fileName = fileNm;
								break;
							}
						}
					}
				}
			}
		}
		return fileName;
	}

3.上传文件,指定目标地址和目标文件名。

	/**
	 *  アップロードファイル
	 * 
	 * @param srcFile アップロードファイル
	 * @param destDirectory ファイル格納先
	 * @return ファイル名
	 * @throws SystemException
	 */
	public static File copyFile(FormFile srcFile, String newFileNameNoExt,  String destDirectory) throws SystemException {
		if (srcFile == null) {
			LogInfo logInfo = new LogInfo("MECO00011", "ファイルが存在しません。");
 			throw new SystemException(logInfo, "E9009");
		}
    	// 画像ファイルをディレクトリパス先に格納する
 		if (StringUtils.isNotEmpty(destDirectory)) {
 			File dest = new File(destDirectory);
 			if (!dest.exists()) {
				LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先:" + destDirectory + "が存在しません。");
	 			throw new SystemException(logInfo, "E9009");
			}
 			if (!dest.isDirectory()) {
 				LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先:" + destDirectory + "がディレクトリではありません。");
	 			throw new SystemException(logInfo, "E9009");
 			}
 			try {
 				String fullFileName = newFileNameNoExt;
 				String ext = getExt(srcFile.getFileName());
 				if (ext != null) {
 					fullFileName += ext;
				}
 				Path destFilePath = Paths.get(destDirectory, fullFileName);
 				Files.copy(srcFile.getInputStream(), destFilePath, StandardCopyOption.REPLACE_EXISTING);
 				return destFilePath.toFile();
 			} catch (IOException e) {
	 			LogInfo logInfo = new LogInfo("MECO00011", e.getMessage());
	 			throw new SystemException(logInfo, "E9009");
 			}
 		} else {
 			LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先:" + destDirectory + "が存在しません。");
 			throw new SystemException(logInfo, "E9009");
 		}
	}

4.备份文件,从哪到哪,备份文件名

UUID.randomUUID().toString()
	/**
	 * バックアップファイル
	 * 
	 * @param srcFileNameNoExt ファイル名
	 * @param srcFileExt 拡張子
	 * @param srcDirectory ファイル格納先
	 * @param destDirectory バックアップフ格納先
	 * @return ファイル名
	 * @throws SystemException
	 */
	public static File backupFile(String srcFileNameNoExt, String srcFileExt, String srcDirectory, String destDirectory) throws SystemException {
		File backup = null;
		if (StringUtils.isEmpty(srcDirectory) || StringUtils.isEmpty(destDirectory)) {
 			return null;
 		}
		try {
			File src = new File(srcDirectory);
			File dest = new File(destDirectory);
			if (src.exists() && dest.exists()) {
				String fullFileName = findFileName(srcDirectory, srcFileNameNoExt, srcFileExt);
				// 指定したファイルが存在の場合
				if (StringUtils.isNotEmpty(fullFileName)) {
					Path srcFilePath = Paths.get(srcDirectory, fullFileName);
					String ext = getExt(fullFileName);
					String newFileName = UUID.randomUUID().toString();
					if (ext != null) {
						newFileName += ext;
					}
	 				Path destFilePath = Paths.get(destDirectory, newFileName);
	 				Files.copy(srcFilePath, destFilePath, StandardCopyOption.REPLACE_EXISTING);
	 				backup = destFilePath.toFile();
				}
			}
			return backup;
		} catch (IOException e) {
 			LogInfo logInfo = new LogInfo("MECO00011", e.getMessage());
 			throw new SystemException(logInfo, "E9009");
		}
	}

5.移动文件

	/**
	 * ファイル移動
	 * 
	 * @param srcFile ファイル
	 * @param destFileNameNoExt ファイル名
	 * @param destDirectory ファイル格納先
	 * @throws SystemException
	 */
	public static void moveFile(File srcFile, String destFileNameNoExt, String destDirectory) throws SystemException {
		if (srcFile == null) {
			LogInfo logInfo = new LogInfo("MECO00011", "ファイルが存在しません。");
 			throw new SystemException(logInfo, "E9009");
		}
    	// 画像ファイルをディレクトリパス先に格納する
 		if (StringUtils.isNotEmpty(destDirectory)) {
 			File dest = new File(destDirectory);
 			if (!dest.exists()) {
				LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先:" + destDirectory + "が存在しません。");
	 			throw new SystemException(logInfo, "E9009");
			}
 			if (!dest.isDirectory()) {
 				LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先がディレクトリではありません。");
	 			throw new SystemException(logInfo, "E9009");
 			}
 			try {
 				String ext = getExt(srcFile.getName());
 				String destFileName = destFileNameNoExt;
 				if (ext != null) {
 					destFileName += ext;
 				}
 				Path destFilePath = Paths.get(destDirectory, destFileName);
 				Files.move(srcFile.toPath(), destFilePath, StandardCopyOption.REPLACE_EXISTING);
 			} catch (IOException e) {
	 			LogInfo logInfo = new LogInfo("MECO00011", e.getMessage());
	 			throw new SystemException(logInfo, "E9009");
 			}
 		} else {
 			LogInfo logInfo = new LogInfo("MECO00011", "ファイル格納先:" + destDirectory + "が存在しません。"); 
 			throw new SystemException(logInfo, "E9009");
 		}
	}

6.删除指定文件

	/**
 	 * ディレクトリの中で、指定したファイルを削除
 	 * @param destDirectory ファイル格納先
 	 * @param fileNameNoExt ファイル名
 	 * @param fileNameSuffix 拡張子
 	 * @throws SystemException
 	 */
 	public static void deleteFileByName(String destDirectory, String fileNameNoExt, String fileNameSuffix) throws SystemException {
 		if (StringUtils.isEmpty(destDirectory)) {
 			return;
 		}
		try {
			File dest = new File(destDirectory);
			if (dest.exists()) {
				String fullFileName = findFileName(destDirectory, fileNameNoExt, fileNameSuffix);
				// 指定したファイルが存在
				if (StringUtils.isNotEmpty(fullFileName)) {
					Path destFile = Paths.get(destDirectory, fullFileName);
 	 				Files.delete(destFile);
				}
			}
		} catch (IOException e) {
 			LogInfo logInfo = new LogInfo("MECO00011", e.getMessage());
 			throw new SystemException(logInfo, "E9009");
		}
 	}

7.删除指定目录(备份用),超过24小时的文件

	/**
 	 * ディレクトリの中で、作成後24時間以上経過したファイルを削除
 	 * @param destDirectory ファイル格納先
 	 * @param fileNameNoExt ファイル名
 	 * @throws SystemException
 	 */
 	public static void deleteFileAfter24Hour(String destDirectory) {
 		if (StringUtils.isEmpty(destDirectory)) {
 			return;
 		}
 		long dayCurrentTimeMillis = 24 * 60 * 60 * 1000;
 		long currentTimeMillis = System.currentTimeMillis();
		File dest = new File(destDirectory);
		File[] files = dest.listFiles();
		if (files != null) {
			long lastModified = 0L;
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				lastModified = file.lastModified();
				if (file.isFile() && (currentTimeMillis - lastModified > dayCurrentTimeMillis)) {
					file.delete();
				}
			}
		}
 	}

8.改变图像大小

   /**
     * 指定したサイズを基に、イメージのサイズを変更する
     * @param is
     * @param baseWidth
     * @param baseHeight
     * @param outputFile
     * @throws SystemException
     */
    public static void resizeImage(InputStream is, double baseWidth, double baseHeight, File outputFile) throws SystemException {
    	ImageInputStream iis = null;
    	String format = null;
    	try {
    		iis = ImageIO.createImageInputStream(is);
    		Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
    		while(it.hasNext()) {
    			ImageReader reader = it.next();
    			format = reader.getFormatName();
    		}
    		BufferedImage srcImage = ImageIO.read(iis);
			if (format == null || srcImage == null || srcImage.getWidth() <= 0 || srcImage.getHeight() <= 0) {
				LogInfo logInfo = new LogInfo("MECO00011", "ファイルが画像ファイルではありません。");
	 			throw new SystemException(logInfo, "E9009");
			}
			double srcWidth = srcImage.getWidth();
			double srcheight = srcImage.getHeight();
			double percent = 0.0;
			if (srcWidth > baseWidth && srcheight > baseHeight) {
				double percentW = baseWidth / srcWidth;
				double percentH = baseHeight / srcheight;
				if (percentW <= percentH) {
					percent = percentW;
				} else {
					percent = percentH;
				}
			} else if (srcWidth > baseWidth) {
				percent = baseWidth / srcWidth;
			} else if (srcheight > baseHeight) {
				percent = baseHeight / srcheight;
			} else {
				// 画像ファイル の幅 ≦画像ファイルの 基準の幅 かつ 画像ファイルの 高さ ≦画像ファイルの 基準の高さの場合
				// イメージのサイズを変更しない
				return;
			}
			int resizedWidth = (int)(srcWidth * percent);
			int resizedHeight = (int)(srcheight * percent);
			BufferedImage resizedImage = new BufferedImage(resizedWidth, resizedHeight, srcImage.getType());
			Graphics graphics = resizedImage.createGraphics();
			graphics.drawImage(srcImage.getScaledInstance(resizedWidth, resizedHeight, Image.SCALE_DEFAULT), 0, 0, null);
			ImageIO.write(resizedImage, format, outputFile); 
		} catch (IOException e) {
			String subinfo = "MethodName:" + e.getStackTrace()[0].getMethodName() + " FileName:"
					+ e.getStackTrace()[0].getFileName() + " Line:"
					+ Format.longToString(e.getStackTrace()[0].getLineNumber());


			LogInfo logInfo = new LogInfo("MECO00011", subinfo);
			throw new SystemException(logInfo, "E9009");
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				String subinfo = "MethodName:" + e.getStackTrace()[0].getMethodName() + " FileName:"
						+ e.getStackTrace()[0].getFileName() + " Line:"
						+ Format.longToString(e.getStackTrace()[0].getLineNumber());


				LogInfo logInfo = new LogInfo("MECO00011", subinfo);
				throw new SystemException(logInfo, "E9009");
			}
		}
    }

    /**
     * 指定したサイズを基に、イメージのサイズを変更する
     * @param srcImg
     * @param baseWidth
     * @param baseHeight
     * @param outputFile
     * @throws SystemException
     */
    public static void resizeImage(File srcImg, double baseWidth, double baseHeight, File outputFile) throws SystemException {
    	if (srcImg == null) {
			LogInfo logInfo = new LogInfo("MECO00011", "ファイルが存在しません。");
 			throw new SystemException(logInfo, "E9009");
		}
    	try {
    		InputStream is = new FileInputStream(srcImg);
			resizeImage(is, baseWidth, baseHeight, outputFile);
		} catch (IOException e) {
			String subinfo = "MethodName:" + e.getStackTrace()[0].getMethodName() + " FileName:"
					+ e.getStackTrace()[0].getFileName() + " Line:"
					+ Format.longToString(e.getStackTrace()[0].getLineNumber());

			LogInfo logInfo = new LogInfo("MECO00011", subinfo);
			throw new SystemException(logInfo, "E9009");
		}
    }
    /**
     * 指定したサイズを基に、イメージのサイズを変更する
     * @param srcImg
     * @param baseWidth
     * @param baseHeight
     * @param outputFile
     * @throws SystemException
     */
    public static void resizeImage(FormFile srcImg, double baseWidth, double baseHeight, File outputFile) throws SystemException {
    	if (srcImg == null) {
			LogInfo logInfo = new LogInfo("MECO00011", "ファイルが存在しません。");
 			throw new SystemException(logInfo, "E9009");
		}
    	try {
			InputStream is = srcImg.getInputStream();
			resizeImage(is, baseWidth, baseHeight, outputFile);
		} catch (IOException e) {
			String subinfo = "MethodName:" + e.getStackTrace()[0].getMethodName() + " FileName:"
					+ e.getStackTrace()[0].getFileName() + " Line:"
					+ Format.longToString(e.getStackTrace()[0].getLineNumber());

			LogInfo logInfo = new LogInfo("MECO00011", subinfo);
			throw new SystemException(logInfo, "E9009");
		}
    	
    }



猜你喜欢

转载自blog.csdn.net/thankna/article/details/80713010