How can I delete the firs开发者_开发问答t two rows of a text file with Java?
Read the file and write back everything but the first two rows.
- Open the file to read, and create a new temp file to write to
- Read line by line, incrementing a line counter, for each line read write that line to the temp file
- Once you hit the index of the lines you want to remove, skip the temp file writing
- Keep on reading until the end of the file
- Rename the temp file to have the original file name
This works if you wish to reference the lines to exclude, by index, like in the example you gave. And it does not load the entire file into memory.
Here is a Guava solution:
public static void removeLines(final File targetFile,
final Charset charSet,
final Collection<Integer> lineNumbers) throws IOException{
final List<String> lines = Files.readLines(targetFile, charSet);
// line numbers need to be sorted in reverse.
// if they are, you can replace everything from Ordering until )){
// with 'lineNumbers){'
for(final Integer lineNumber : Ordering
.natural()
.reverse()
.immutableSortedCopy(lineNumbers)){
lines.remove(lineNumber.intValue());
}
Files.write(Joiner.on('\n').join(lines), targetFile, charSet);
}
Yes, the entire file is read into memory, so don't try this with huge server log files.
Very good example of reading a file here: http://www.kodejava.org/examples/266.html
Here is how I am deleting first 20 lines from the targetFile...
class removeLines{
public static void main(String[] args){
try{
//Here I am opening the target File named 1.txt......
File targetFile = new File("1.txt");
BufferedReader targetBuf = new BufferedReader(new FileReader(targetFile));
//Opening a Temp file.......
File tempFile = new File("temp.txt");
PrintWriter printTemp = new PrintWriter(tempFile);
//Here is the important part... skipping first 20 lines....
for(int i=1;i<=20;i++){
targetBuf.readLine();
}
String notfau;
while((notfau = targetBuf.readLine())!=null){
printTemp.println(notfau);
}
//closing the files after finished copying from target file to temp file....
targetBuf.close();
printTemp.close();
//Now replace and delete the target file with temp file....
targetFile.delete();
tempFile.renameTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here's how:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
// Construct the new file that will later be renamed
// to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
精彩评论