Skip to content

Instantly share code, notes, and snippets.

@JimmyFrix
Created January 23, 2012 00:29
Show Gist options
  • Save JimmyFrix/1659614 to your computer and use it in GitHub Desktop.
Save JimmyFrix/1659614 to your computer and use it in GitHub Desktop.
A utility to remove line numbers from a file which contains the number of the line at the beginning of that line for each line.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class LineNumberRemover {
public static void main(String... arguments) throws IOException {
if (arguments.length < 1) {
System.out.println("Please supply the path of the file to" +
" remove line numbers from in the command-line arguments.");
return;
}
List<String> new_lines = readAndRemove(arguments[0]);
writeNewFile(new_lines, arguments[0]);
}
private static List<String> readAndRemove(String file_path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file_path));
List<String> new_lines = new ArrayList<String>();
try {
for (int i = 1; i < Integer.MAX_VALUE; i++) {
String line = reader.readLine();
if (line != null) {
if (line.contains(String.valueOf(i))) {
String new_line = line.substring(line.indexOf(String.valueOf(i)) + String.valueOf(i).length());
new_lines.add(new_line);
}
} else {
break;
}
}
} finally {
reader.close();
}
return new_lines;
}
private static void writeNewFile(List<String> new_lines, String old_file_path) throws IOException {
File new_file = new File(old_file_path + ".new");
new_file.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(new_file));
try {
for (String line : new_lines) {
writer.write(line + "\n");
}
} finally {
writer.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment