简体   繁体   English

如何写入和读取同一文件

[英]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. 我试过使用PrintWriter和FileWriter,短暂尝试BufferedWriter和其他解决方案都无济于事。 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." 每次尝试创建PrintWriter时,都会给我bw参数一个错误:“变量fw可能尚未初始化。”

Does anyone know how to solve this issue? 有谁知道如何解决这个问题?

"variable fw might not have been initialized." “变量fw可能尚未初始化。”

You need to see more closely your code. 您需要更仔细地查看您的代码。 The IDE saw this scenario. 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);

Workarounds for this... 解决方法...

Scenario 1 场景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 方案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){

    }

And so on... 等等...

The error "variable fw might not have been initialized" will get resolved by simply initializing your variable fw to null! 只需将变量fw初始化为null即可解决“变量fw可能尚未初始化”错误!

FileWriter fw = null; FileWriter fw = null; is correct. 是正确的。

--Thanks for asking. -谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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