Reputation: 1167
I'm trying to write a method in Java that removes the first line of a file.
First idea (rejected because calling .exec is not a good practice)
public void removeHeader(String fileName) throws IOException, InterruptedException {
if (StringUtils.isBlank(fileName)) {
throw new IllegalArgumentException("fileName was empty");
}
Process p = Runtime.getRuntime().exec("sed -i 1d " + fileName);
if (p.waitFor() != 0) {
throw new IOException("Failed to remove the header from " + fileName);
}
}
Second idea (rejected in CR because iterating over every line and writing it into a new file is slow and not stylish).
public void removeHeader(String fileName) throws IOException, InterruptedException {
if (StringUtils.isBlank(fileName)) {
throw new IllegalArgumentException("fileName was empty");
}
File inFile = new File(fileName);
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader(fileName));
pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
boolean first = true;
while ((line = br.readLine()) != null) {
if (!first) {
pw.println(line);
pw.flush();
}
first = false;
}
}
finally {
pw.close();
br.close();
}
if (inFile.exists() && tempFile.exists()) {
inFile.delete();
tempFile.renameTo(inFile);
}
}
I want my solution to work regardless of newline format and be easy to read. Is there a solution that meets all these needs?
Upvotes: 2
Views: 4510
Reputation: 468
Your code can be shortened like this (requires Java7):
FileInputStream
But otherwise, as other said, there's no easy way to cut out the first part of a file.
Upvotes: 0
Reputation: 41137
You have to read and copy anything you want to keep (Even sed
is doing that).
The second version can be improved slightly by simply skipping the first line by a separate read before the loop and then you won't have to check whether you're on the first line every time through the loop.
The second could also gain a bit of elegance by writing a FilterReader that skips the first line. It's not likely worth the trouble for this purpose, but learning to implement such a filter is worthwhile.
Upvotes: 2
Reputation: 125708
I'm not a Java person, but there's no way (Java or otherwise) to remove content from the beginning of a file without rewriting the remaining content (unless you can access the underlying file system to move the starting block of the file, which would defeat your "easy to read" requirement).
I sense premature optimization here, unless the files are really large.
Upvotes: 9