Code:
import java.io.*;
import java.util.*;
public class FileUpdater {
private String filePath=null;
public final static String BACKUP_PATH="c:\\tmp\\bcup.txt";
//
public FileUpdater(String filePath) {
this.filePath=filePath;
}
public void updateFile () throws IOException {
ArrayList recordList=new ArrayList();
// get file buffer as an arraylist of records
BufferedReader br=new BufferedReader(new FileReader(filePath));
String line=null;
while ((line=br.readLine())!=null) {
recordList.add(line);
}
br.close();
// scan file buffer's records and perform updates where required.
// if no edit required then leave as is
int edCount=0;
for (int i=0; i<recordList.size(); i++) {
String inLine=(String)recordList.get(i);
/**
* check edit conditions and return new line if edited
*/
String newLine=checkForEdit(inLine);
if (newLine!=null) {
recordList.set(i,newLine); // replace line
edCount++;
}
}
System.out.println("\n\nIn file "+filePath+" "+
edCount+" lines of "+recordList.size()+" lines have been edited");
/**
* file buffer is prepared, backup the old version, overwrite and exit
*/
// backup
br = new BufferedReader(new FileReader(filePath));
BufferedWriter bw = new BufferedWriter(new FileWriter(BACKUP_PATH));
while ( (line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
System.out.println("Backed up old version of " + filePath + " to " +
BACKUP_PATH);
// store
bw = new BufferedWriter(new FileWriter(filePath));
for (int i = 0; i < recordList.size(); i++) {
line = (String) recordList.get(i);
bw.write(line);
bw.newLine();
}
bw.close();
System.out.println("Saved updates to: " + filePath + " records: " +
recordList.size());
}
/**
* Stupid example but made just to have a runthrough
* @param inLine
* @return
*/
private String checkForEdit (String inLine) {
int pos=inLine.indexOf("text");
if (pos > 0) {
return inLine+" [text found at pos: "+pos+"]";
} else {
return null;
}
}
/**
* ************************ MAIN *********************
* @param args
*/
public static void main(String[] args) {
FileUpdater fu = new FileUpdater("c:\\tmp\\test.txt");
try {
fu.updateFile();
System.out.println("FileUpdater finished");
}
catch (IOException ex) {
System.out.println("FileUpdater failed");
ex.printStackTrace();
}
}
}
Bookmarks