Advertisement
Guest User

Java code

a guest
Apr 18th, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8.  
  9. public class dd {
  10.  
  11.  
  12.   public void removeLineFromFile(String file, String lineToRemove) {
  13.  
  14.     try {
  15.  
  16.       File inFile = new File(file);
  17.      
  18.       if (!inFile.isFile()) {
  19.         System.out.println("Parameter is not an existing file");
  20.         return;
  21.       }
  22.        
  23.       //Construct the new file that will later be renamed to the original filename.
  24.       File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
  25.      
  26.       BufferedReader br = new BufferedReader(new FileReader(file));
  27.       PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
  28.      
  29.       String line = null;
  30.  
  31.       //Read from the original file and write to the new
  32.       //unless content matches data to be removed.
  33.       while ((line = br.readLine()) != null) {
  34.        
  35.         if (!line.trim().equals(lineToRemove)) {
  36.  
  37.           pw.println(line);
  38.           pw.flush();
  39.         }
  40.       }
  41.       pw.close();
  42.       br.close();
  43.      
  44.       //Delete the original file
  45.       if (!inFile.delete()) {
  46.         System.out.println("Could not delete file");
  47.         return;
  48.       }
  49.      
  50.       //Rename the new file to the filename the original file had.
  51.       if (!tempFile.renameTo(inFile))
  52.         System.out.println("Could not rename file");
  53.      
  54.     }
  55.     catch (FileNotFoundException ex) {
  56.       ex.printStackTrace();
  57.     }
  58.     catch (IOException ex) {
  59.       ex.printStackTrace();
  60.     }
  61.   }
  62.  
  63.   public static void main(String[] args) {
  64.     dd util = new dd();
  65.     util.removeLineFromFile("test.txt", "");
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement