Replace blocks in files, which are identified by a start and an end token.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Scanner; | |
public class ReplaceBlocks { | |
private static final String FIRST_LINE_TO_REPLACE = "<<<"; | |
private static final String LAST_LINE_TO_REPLACE = ">>>"; | |
private final List<String> replacement; | |
public ReplaceBlocks(String pathnameOfReplacement) | |
throws FileNotFoundException { | |
replacement = readFile(pathnameOfReplacement); | |
} | |
public void applyTo(String pathname) throws Exception { | |
Iterator<String> source = readFile(pathname).iterator(); | |
FileWriter writer = new FileWriter(pathname); | |
copyLinesUntilFirstLineToReplace(source, writer); | |
writeReplacementToWriter(writer); | |
skipLinesToReplace(source); | |
copyUntilEnd(source, writer); | |
writer.close(); | |
} | |
private List<String> readFile(String pathname) throws FileNotFoundException { | |
File file = new File(pathname); | |
Scanner scanner = new Scanner(file); | |
List<String> lines = new ArrayList<String>(); | |
while (scanner.hasNextLine()) { | |
lines.add(scanner.nextLine()); | |
} | |
scanner.close(); | |
return lines; | |
} | |
private void copyLinesUntilFirstLineToReplace(Iterator<String> source, | |
FileWriter writer) throws IOException { | |
while (source.hasNext()) { | |
String line = source.next(); | |
if (FIRST_LINE_TO_REPLACE.equals(line)) { | |
break; | |
} else { | |
writeLine(writer, line); | |
} | |
} | |
} | |
private void writeReplacementToWriter(FileWriter writer) throws IOException { | |
for (String line : replacement) { | |
writeLine(writer, line); | |
} | |
} | |
private void skipLinesToReplace(Iterator<String> source) { | |
while (source.hasNext()) { | |
String line = source.next(); | |
if (LAST_LINE_TO_REPLACE.equals(line)) { | |
break; | |
} | |
} | |
} | |
private void copyUntilEnd(Iterator<String> source, FileWriter writer) | |
throws IOException { | |
while (source.hasNext()) { | |
String line = source.next(); | |
writeLine(writer, line); | |
} | |
} | |
private void writeLine(FileWriter writer, String line) throws IOException { | |
writer.write(line); | |
writer.write("\n"); | |
} | |
public static void main(String[] args) throws Exception { | |
ReplaceBlocks replacer = new ReplaceBlocks(args[0]); | |
for (int i = 1; i < args.length; ++i) { | |
replacer.applyTo(args[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment