- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.StringTokenizer;
- import java.util.UUID;
- public class RandomName {
- public static void main(String agrs[]) {
- ArrayList<HashMap<String, Object>> files = new ArrayList<HashMap<String, Object>>();
- HashMap<String, Object> map = new HashMap<String, Object>();
- String extName = "";
- String fileName = "";
- String seq= "";
- // 버퍼 생성
- BufferedReader br = null;
- // Input 스트림 생성
- InputStreamReader isr = null;
- // File Input 스트림 생성
- FileInputStream fis = null;
- // File 경로
- File file = new File("C:\\files.txt");
- // 버퍼로 읽어들일 임시 변수
- String temp = "";
- try {
- // 파일을 읽어들여 File Input 스트림 객체 생성
- fis = new FileInputStream(file);
- // File Input 스트림 객체를 이용해 Input 스트림 객체를 생서하는데 인코딩을 UTF-8로 지정
- isr = new InputStreamReader(fis, "EUC-KR");
- // Input 스트림 객체를 이용하여 버퍼를 생성
- br = new BufferedReader(isr);
- // 버퍼를 한줄한줄 읽어들여 내용 추출
- int cnt = 0;
- while ((temp = br.readLine()) != null) {
- StringTokenizer st = new StringTokenizer(temp, "&&");
- while(st.hasMoreTokens()) {
- if(cnt == 0) {
- map = new HashMap<String, Object>();
- map.put("seq", st.nextToken());
- cnt++;
- } else {
- map.put("filename", st.nextToken());
- files.add(map);
- cnt = 0;
- }
- }
- }
- for(int i=0; i<files.size(); i++) {
- HashMap<String, Object> tempMap = new HashMap<String, Object>();
- tempMap = files.get(i);
- seq= tempMap.get("seq").toString();
- extName = getFileExt(tempMap.get("filename").toString());
- fileName = Long.toString(System.currentTimeMillis()) + "_" + getRandomStr(8)+"." +extName; //실제 저장되는 파일 이름.
- File oriFile = new File("C:/Users/user/Desktop/upload/" + tempMap.get("filename").toString());
- File convFile = new File("C:/Users/user/Desktop/upload/" + fileName);
- oriFile.renameTo(convFile);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- fis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- isr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- br.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // 랜덤 문자열 반환
- public static String getRandomStr(int length) {
- String rtnVal = "";
- String str = UUID.randomUUID().toString();
- if(str.length() > length)
- rtnVal = str.substring(0, length);
- return rtnVal;
- }
- public static String getFileExt(String filename) {
- String ext = "";
- if(filename==null || "".equals(filename)) {
- ext = "";
- } else {
- if(filename.indexOf(".")>-1) {
- ext = filename.substring(filename.lastIndexOf(".")+1, filename.length());
- }
- }
- return ext;
- }
- }
2015년 12월 3일 목요일
파일업로드 및 파일명 변경
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기