Created
May 15, 2016 16:54
-
-
Save sangpt/32ba1fbf8e369e99df1c94141d0c3285 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package common; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
public class NewClass { | |
public static void main(String[] args) { | |
NewClass rlf = new NewClass(); | |
rlf.removeLineFromFile("E:\\test.txt", "123"); | |
} | |
public void removeLineFromFile(String file, String lineToRemove) { | |
try { | |
File inFile = new File(file); | |
if (!inFile.isFile()) { | |
System.out.println("Parameter is not an existing file"); | |
return; | |
} | |
//Construct the new file that will later be renamed to the original filename. | |
File tempFile = new File(inFile.getAbsolutePath() + ".txt"); | |
BufferedReader br = new BufferedReader(new FileReader(file)); | |
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) { | |
String[] arr = line.split("="); | |
for (String i : arr) { | |
if (!i.trim().equals(lineToRemove)) { | |
pw.println(i); | |
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment