/**
* 텍스트 파일 생성.
* @param filePath 생성 파일 경로
* @param fileName 생성 파일 명
* @param encoding 생성 할 인코딩
* @param text 문자열
* @param isOverWrite true : 파일이 존재할 경우 새 문자열로 내용 변경, false : 파일이 존재할 경우 새 문자열 내용 추가
* @return true : 파일 생성 성공, false : 파일 생성 실패
*/
public static boolean writeTextFile(String filePath, String fileName, String encoding, String text, boolean isOverWrite) throws IOException{
if(filePath == null || filePath.length() <= 0 ||
fileName == null || fileName.length() <= 0){
return false;
}
File textFileFolder = new File(filePath);
if(!textFileFolder.exists()){
textFileFolder.mkdirs();
}
File textFile = new File(filePath, fileName);
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(textFile, !isOverWrite), Charset.forName(encoding)));
bw.write(text);
bw.flush();
} catch (Exception e){
throw new IOException(e);
} finally {
try{
bw.close();
}catch (Exception e){
// ignore
}
}
return true;
}
/**
* 텍스트 파일 읽어서 반환.
* @param filePath 읽을 파일 경로
* @param fileName 읽을 파일 명
* @param encoding 읽어 드릴 인코딩
* @return null : 경로 없음, 파일 없음, 오류 발생, 문자열 : 정상 반환
*/
public static String readTextFile(String filePath, String fileName, String encoding){
if(filePath == null || filePath.length() <= 0 ||
fileName == null || fileName.length() <= 0){
return null;
}
File textFile = new File(filePath, fileName);
if(!textFile.exists()){
return null;
}
StringBuilder result = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(textFile), Charset.forName(encoding)));
String readLine = "";
while (((readLine = br.readLine()) != null)) {
result.append(readLine + "\n");
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
br.close();
} catch (Exception e) {
// ignore
}
}
return result.toString();
}