Question

I am trying to remove some records from a Properties file but my code removes all the records. What am I doing wrong?

import java.io.*;


public class FileCheck {

    private final String HOST_KEY = "database.host";
    private final String SID_KEY = "database.sid";
    private final String USER_KEY = "database.user";
    private final String PASS_KEY = "database.pass";
    private final String FROMEMAIL_KEY = "fromemailid";
    private final String FROMEMPASS_KEY = "fromemailpass";
    private final String USETLS_KEY = "usetls";
    private final String MAILSERVER_KEY = "emailserverhost";
    private final String OUTGOINGPORT_KEY = "outgoingemailport";

    public FileCheck() {

    }
 public void removeEditableProperties() {
        BufferedReader reader;
        BufferedWriter writer;
        try {
            File inputFile = new File("BiDBProperties.properties");
            File tempFile = new File("BiDBProperties_temp.properties");

            reader = new BufferedReader(new FileReader(inputFile));
            writer = new BufferedWriter(new FileWriter(tempFile));
            String currentLine;

            while ((currentLine = reader.readLine()) != null) {
                String trimmedLine = currentLine.trim();

                if (trimmedLine.startsWith(HOST_KEY) || trimmedLine.startsWith(SID_KEY)
                        || trimmedLine.startsWith(USER_KEY) || trimmedLine.startsWith(PASS_KEY)
                        || trimmedLine.startsWith(FROMEMAIL_KEY)
                        || trimmedLine.startsWith(FROMEMPASS_KEY) || trimmedLine.startsWith(USETLS_KEY)
                        || trimmedLine.startsWith(MAILSERVER_KEY) || trimmedLine.startsWith(OUTGOINGPORT_KEY)) {
                    continue;
                }
                writer.write(currentLine);
                writer.newLine();
                writer.flush();
            }
            writer.close();
            reader.close();

            if (!inputFile.delete()) {
                System.out.println("ERROR: Operation Failed. Please Try again");
                return;
            }
            if (!tempFile.renameTo(inputFile)) {
                System.out.println("ERROR: Operation Failed. Please Try again");
            }

        } catch (IOException asd) {
            System.out.println(asd.getMessage());
        }
    }

}

Is there something I am doing wrong??

Was it helpful?

Solution

It is working perfectly for me.. removing required properties from BiDBProperties.properties file..please close both files before running your program and try again

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top