我正在尝试用 Java 编写一个删除文件第一行的方法。
第一个想法(被拒绝,因为调用 .exec 不是一个好习惯)
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);
}
}
第二个想法(在 CR 中被拒绝,因为遍历每一行并将其写入新文件很慢且不时尚)。
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);
}
}
无论换行格式如何,我都希望我的解决方案能够正常工作并且易于阅读。是否有满足所有这些需求的解决方案?