Click to See Complete Forum and Search --> : [RESOLVED] clear text in a file
Justa Lol
Jul 28th, 2009, 10:34 AM
i need to know how to find one line in a file and delete that line only.
like if i type "text" in a textfield then i click a button and it finds the line in a file where it says "text" and after that clears only that line.
ComputerJy
Jul 28th, 2009, 12:03 PM
This code should do it:import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(final String[] args) throws IOException {
final Scanner scanner = new Scanner(System.in);
String filePath = null;
do {
filePath = scanner.nextLine();
} while (new File(filePath).exists());
final String lineToDelete = scanner.nextLine();
final BufferedReader reader = new BufferedReader(new FileReader(
filePath));
final StringBuffer sb = new StringBuffer();
while (reader.ready()) {
final String currentLine = reader.readLine();
if (!currentLine.equals(lineToDelete)) {
sb.append(reader.readLine());
sb.append(System.getProperty("line.separator"));
}
}
reader.close();
final FileWriter writer = new FileWriter(filePath);
writer.write(sb.toString());
writer.close();
}
}
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.