如何写入和读取同一个文件

How to write to and read from the same file

我当前的问题是我想写入文件和从文件读取,但是,我一直试图抛出异常并实例化我的变量,结果却不断收到关于我声明变量的方式的错误'could not have been instantiated.' 我不确定如何解决这个问题。

我尝试过使用 PrintWriter 和 FileWriter,短暂地尝试过 BufferedWriter 和其他解决方案无济于事。我不知道还能尝试什么。

{
    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);

    }
}

每次我尝试创建 PrintWriter 时,它都会给我 bw 参数错误:"variable fw might not have been initialized."

有谁知道如何解决这个问题?

"variable fw might not have been initialized."

您需要更仔细地查看您的代码。 IDE 看到了这个场景。

    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);

此问题的解决方法...

场景一

    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);

场景 2 移至 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){

    }

等等...

只需将您的变量 fw 初始化为 null 即可解决错误 "variable fw might not have been initialized"!

FileWriter fw = null; is correct.

--感谢提问