Android remove line from text file

My app Yahrtzeit2 got new option – possibility to remove unneeded dates from the list.
For this purpose I added the following code:

BufferedReader in = null;
 out = null;
File sdCard = Environment.getExternalStorageDirectory();
File root = new File (sdCard.getAbsolutePath() + "/yahrtzeit2");
try {
       	InputStream instream = new FileInputStream(file);
       	in = new BufferedReader(new InputStreamReader(instream));
       	out = new PrintWriter(new File(root,"myYahrtzeits_back"));
					
        String line; //a line in the file
		        
	while ((line = in.readLine()) != null) {
	        if (!Pattern.matches("^some pattern.*",line)) { //find the line we want to replace
	                  out.println(line); //if it's not the line, just output it as-is
	        }
					        
	}
				
	in.close();
	out.flush();
        out.close();
        File oldFile = new File (root,"/myYahrtzeits");
        oldFile.delete();
        File newFile = new File (root,"/myYahrtzeits_back");
        newFile.renameTo(oldFile);
}catch(Exception e) { 
	Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); 
}

The algorithm is very simple:
– read from source file
– while reading, write to destination file
– during this process find the matched line and skip it.
– remove old file
– new file rename to old one’s name.

Leave a Reply

%d bloggers like this: