I need to be able to delete a line based on specific text in the line (not whole line).
so far this is what i have, but it is deleting the whole file!! i am probably missing a semi colon or something silly.. can some one please help out?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class DeleteStudent
{
public static void removeStudentData()
{
File inputFile = new File("StudentsII.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(inputFile));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
CharSequence sID = null;
String lineToRemove = (String) sID;
String currentLine;
Scanner UI = new Scanner(System.in);
boolean found = false;
System.out.println("\n***DELETE STUDENT RECORD***\n");
System.out.println("Enter a student ID: ");
sID=UI.next();
try {
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.contains(sID))
continue;
try {
writer.write(currentLine);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean successful = tempFile.renameTo(inputFile);
Menu.displayMenu();
}
}
txt file contains following info…
Martha Stewart 123 Freshman
Cindi Lauper 234 Senior
Tina Turner 345 Freshman
You need to close the streams and files after you’re done writing: