cos.jar 의 FileRenamePolicy 만들기.

Published on: 2011. 2. 15. 09:52 by louis.dev

MultipartRequest를 통해 업로드를 하면, 생성자에 FileRenamePolicy 인스턴스를 파라미터로 전달합니다.

일반적으로 DefaultFileRenamePolicy를 많이 사용하게 되는데요.

이 DefaultFileRenamePolicy는 간단한 역할을 합니다.

public class DefaultFileRenamePolicy implements FileRenamePolicy {
  
  // This method does not need to be synchronized because createNewFile()
  // is atomic and used here to mark when a file name is chosen
  public File rename(File f) {
    if (createNewFile(f)) {
      return f;
    }
    String name = f.getName();
    String body = null;
    String ext = null;

    int dot = name.lastIndexOf(".");
    if (dot != -1) {
      body = name.substring(0, dot);
      ext = name.substring(dot);  // includes "."
    }
    else {
      body = name;
      ext = "";
    }

    // Increase the count until an empty spot is found.
    // Max out at 9999 to avoid an infinite loop caused by a persistent
    // IOException, like when the destination dir becomes non-writable.
    // We don't pass the exception up because our job is just to rename,
    // and the caller will hit any IOException in normal processing.
    int count = 0;
    while (!createNewFile(f) && count < 9999) {
      count++;
      String newName = body + count + ext;
      f = new File(f.getParent(), newName);
    }

    return f;
  }

  private boolean createNewFile(File f) {
    try {
      return f.createNewFile();
    }
    catch (IOException ignored) {
      return false;
    }
  }
}


코드에서 보시다 시피 중복된 파일이 있으면 파일이름 뒤에 1~9999까지의 숫자를 붙여서 파일의 rename을 진행하고 있는것을 확인 할 수 있습니다.

만약 서버의 업로드 서버의 인코딩 설정 문제로 한글이 깨지거나 할수 있습니다. 그렇기 때문에 저는 Timestamp를 통해 파일이름을 변경하고 있습니다. 이렇듯 MultipartRequest에서 File Rename Policy를 Timestamp로 변경하는 방법을 진행해 보겠습니다.

package net.tutorial.util;

import java.io.File;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class TimestampFileRenamePolicy implements FileRenamePolicy {
	@Override
	public File rename(File f) {
		String name = f.getName();
		String body = null;
		String ext = null;

		int dot = name.lastIndexOf(".");
		if (dot != -1) {
			ext = name.substring(dot); // includes "."
		} else {
			ext = "";
		}
		body = Long.toString( System.currentTimeMillis() );

		File renameFile = new File( f.getParent(), body + ext );
		
		if( renameFile.exists() ){
			int count = 0;
			do {
				count++;
				String newName = body + count + ext;
				renameFile = new File(f.getParent(), newName);
			}while( renameFile.exists() && count < 9999 );
			
		}
		f.renameTo( renameFile );
		return renameFile;
		
	}
}


System.currentTimeMillis()를 통해 현재의 시간을 ms 단위로 구한뒤에 이를 파일이름에 붙입니다. 만약 그럴일은 없겠지만..^^ 동시에 파일 업로드를 진행해서 파일이름이 똑같다면, Timestamp뒤에 1~9999를 붙여서 처리하는 TimeStampRenamePolicy를 만들어 보았습니다.