FileUtil.java 2.88 KB
package com.batch.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

import org.springframework.core.io.ClassPathResource;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class FileUtil {

	public static StringBuffer readFileToString(String resourceName) {
		StringBuffer sb = new StringBuffer();
		try {
			ClassPathResource resource = new ClassPathResource(resourceName);
			BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));

			// br.readLine() 이 null 인지 검사할 때 한번 사용되므로 String 에 먼저 저장해둬야한다.
			String s = "";
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
		} catch (Exception e) {
			sb.append(e.getStackTrace());
		}
		return sb;
	}

	/**
	 * 파일 마지막 부터 lineCnt행 읽기
	 * @param resourceName
	 * @param lineCnt
	 * @return
	 */
	public static StringBuffer readFileLastLines(String resourceName, int lineCnt) {
		StringBuffer sb = new StringBuffer();

//		lineCnt = 50; // test case
//		resourceName = "D://logs/localhost_access_log.2019-03-26.txt"; // test case
		
		if(resourceName == null || resourceName.isEmpty()) {
			sb.append("파일 경로가 입력되지 않았습니다.");
		}else if(lineCnt < 1) {
			sb.append("라인갯수가 입력되지 않았습니다.");
		}else {
			RandomAccessFile rf = null;
		
			try {
				
				rf = new RandomAccessFile(resourceName, "r");
				long len = rf.length();
				for (long i = len - 1; i >= 0; i--) {
					rf.seek(i);
					char c = (char) rf.read();
					if (c == '\n') {
						lineCnt--;
						if(lineCnt < 0) {
							break;
						}
					}
					
					sb.insert(0, c);
				}
				
				/*** TODO : 필요 시 파일 인코딩. utf-8 **/
//				sb = new StringBuffer(new String((sb.toString()).getBytes("ISO-8859-1"), "UTF-8"));

			} catch (Exception e) {
//				e.printStackTrace();
				sb = new StringBuffer("유효한 파일경로가 아닙니다.("+resourceName+")");
			} finally {
				if (rf != null) {
					try {
						rf.close();
					} catch (IOException e) {
//						e.printStackTrace();
						sb = new StringBuffer("유효한 파일경로가 아닙니다.("+resourceName+")");
					}
				}
			}
		}
		return sb;
	}

	public static JsonObject strToJsonObj(String jsonString) {
		JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
		return jsonObject;
	}

	public static Object strToObj(String jsonString, Class<?> anyClass) {
		Gson gson = new Gson();
		Object convertedObject = gson.fromJson(jsonString, anyClass);
		return convertedObject;
	}

	public static String objToStr(Object obj) {
		Gson gson = new Gson();
		String stringObject = gson.toJson(obj);
		return stringObject;
	}

}