Borrar Linea de un fichero txt
Publicado por abel (1 intervención) el 27/06/2008 01:26:25
buenas, estoy trabajando con un archivo txt, este consta de varias (registros) y cada uno de los registros estan didido en campos usando el caracter #, quisiera poder eliminar una fila determinada del archivo, la funcion q utilizo le paso por parametro la linea q quiero eliminar del archivo(reservas.txt) pero no me resulta, nose si me podrian ayudar:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public void removeLineFromFile(String lineToRemove) {
try {
File inFile = new File("c:/reservas.txt");
if (!inFile.isFile()) {
System.out.println("no hay 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("c:/reservas.txt"));
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();
}
}
Valora esta pregunta


1