简体   繁体   中英

How to write to and read from the same file

My current problem is that I would like to write to and read from a file, however, I keep trying to throw exceptions and instantiating my variables only to keep getting errors about how the variables I've declared 'could not have been instantiated.' I'm unsure how to fix this problem.

I've tried using PrintWriter and FileWriter, briefly tried BufferedWriter and other solutions to no avail. I do not know what else I can try.

{
    public SettingsHandler()
    {
        File configFile=new File(this.getClass().getResource("file").getFile());
        try{
            file = new Scanner(configFile);
        }catch (FileNotFoundException e){
            System.out.println("Config.ini not found");
        }
    }

    public void saveSetting(String setting, String value)
    {
        FileWriter fw;
        try{
            fw = new FileWriter("myfile.txt", true);
        }catch (IOException e){

        }
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);

    }
}

Every time I try creating the PrintWriter, it gives me an error for the bw parameter: "variable fw might not have been initialized."

Does anyone know how to solve this issue?

"variable fw might not have been initialized."

You need to see more closely your code. The IDE saw this scenario.

    FileWriter fw;
    try{
        fw = new FileWriter("myfile.txt", true); ==> An exception can happen
    }catch (IOException e){
           nothing to do... 
    }
    BufferedWriter bw = new BufferedWriter(fw); ==> fw is not initialized..
    PrintWriter out = new PrintWriter(bw);

Workarounds for this...

Scenario 1

    FileWriter fw = null; // Very pointles...
    try{
        fw = new FileWriter("myfile.txt", true);
    }catch (IOException e){

    }
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);

Scenario 2 Move to the try catch

    try{
      FileWriter   fw = new FileWriter("myfile.txt", true); //Well a little better
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);
    }catch (IOException e){

    }

And so on...

The error "variable fw might not have been initialized" will get resolved by simply initializing your variable fw to null!

FileWriter fw = null; is correct.

--Thanks for asking.

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