简体   繁体   中英

need to delete a line of text from a file if it contains specific data in Java

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:

writer.close();
tempFile.close();
//etc.

Use a debugger (or just println) to see which bits of your code are being exercised. eg print sID and trimmedLine - are they what you expect?

On a quick look I can't see any actual errors, but a few style things (which can often help make the code more readable so that errors are easier to find)

Variable called UI is a bit confusing - looks like a class name or something (due to the leading capital) - it's 100% legal code but you won't see too many programmers using that sort of naming convention for local variables.

if (condition) continue;

Is slightly odd - I can see it works, but would be a bit more obvious to write it as

if (!condition) { /* write the line */ }

A brief look, I find this code below suspicious. tempFile.renameTo(inputFile);

The reason is the temp file wants to be renamed to an input file, which it has not been properly closed. This should cause a File IO error, to my opinion.

Perhaps tomorrow, I will use the Eclipse debugger to be certain of the issue. But you should do the same. If you reward me with your vote for the best answer, that will give me the incentive to do so :)

Question Which file got deleted as you said? Is it the temp file, my guess?

Good luck,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM