Language/Java

File 내 특정 Context 교체

아르비스 2016. 7. 21. 21:07

File 내의 특정 문구를 변경해서 새로운 file로 만드는 예제


필요 사항

inputFileName(경로 포함)

outputFileName(경로 포함)

Properties(변경 문구, key=value)

return 성공여부



import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.util.Map.Entry;

import java.util.Properties;


import lombok.Data;


@Data

public class FileConvertObject {

private String inFileName;

private String outFileName;

private File inputFile;

private File outputFile;

private FileInputStream fileInputStream;

private FileOutputStream fileOutputStream;

private BufferedReader bufferedReader;

private BufferedWriter bufferedWriter;

private Properties prop;

private boolean init;


public void init() {

setInputFile(new File(getInFileName()));

setOutputFile(new File(getOutFileName()));

try {

setFileInputStream(new FileInputStream(getInputFile()));

setFileOutputStream(new FileOutputStream(getOutputFile()));

setBufferedReader(new BufferedReader(new InputStreamReader(getFileInputStream())));

setBufferedWriter(new BufferedWriter(new OutputStreamWriter(getFileOutputStream())));

} catch (FileNotFoundException e) {

e.printStackTrace();

}

setInit(true);

}

public boolean convert() {

boolean result = false;

String line;

String repLine=null;

if(isInit()) {

try {

while ((line = getBufferedReader().readLine()) != null) {

for (Entry<Object, Object> entry : prop.entrySet()) {

repLine = line.replaceAll((String)entry.getKey(), (String)entry.getValue());

}

getBufferedWriter().write(repLine);

getBufferedWriter().newLine();

}

result = true;

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

getBufferedReader().close();

} catch (IOException e) {

e.printStackTrace();

}

try {

getBufferedWriter().close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return result;

}

}