How to delete a string inside a file (.txt) in Java Programming
I would like to delete a string or a line inside a ".txt" file (for example filen.txt). For example, I have these lines in the file:
1JUAN DELACRUZ
2jUan dela Cruz 3Juan Dela Cruz
Then delete the 2nd line (2jUan dela Cruz
), so the ".t开发者_开发百科xt" file will look like:
1JUAN DELACRUZ
3Juan Dela Cruz
How can I do this?
1) Scan the file line by line, and write the results in another temporary file.If you encounter the String within a line, remove it, and write only the modified line.
2) Remove the intial file, and rename the temporary file with the name of the initial file.
In order to achieve this, take a look at the File class.
File file = new File("data.txt");
Then "scan" the file using the Scanner class, as in the following example:
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
/* Proccess line */
}
To write information into a new File, take a look at PrintWriter class.
LATER EDIT:
If you feel confortable with the concept of buffers, you can also use BufferedReader with its read function, in order to process bigger chunks of data, instead of "lines".
Get a string with everything from the file in it. Remove what you want. Write the string back to the file, removing all of what was there before. Simple.
If the file is small and it is not a homework, get the apache commons IO and read the file to a String to manipulate it. Download: http://commons.apache.org/io/download_io.cgi How to read: http://www.javadb.com/how-to-read-file-contents-to-string-using-apache-commons-io How to write: http://www.kodejava.org/examples/55.html
this is really easy just read your file into a string and split that string into the string you want to delete (in your case "2jUan dela Cruz")
in order to load your file into a string use this simple code: (according to this page)
String text = new Scanner( new File("poem.txt") ).useDelimiter("\\A").next();
String[] Splite= text.split("2jUan dela Cruz");
int size= Splite.length;
String NewText;
for(i=0; i<size ; i++){
NewText+=Splite[i];
}
// now your NewText String is ready to be written to your File
精彩评论