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

标签 java file-io

我当前的问题是,我想写入和读取文件,但是,我一直尝试抛出异常并实例化我的变量,只是为了不断收到有关我声明的变量“不可能”的错误实例化。我不确定如何解决这个问题。

我尝试过使用 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 参数错误:“变量 fw 可能尚未初始化。”

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

最佳答案

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

此问题的解决方法...

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

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

    }

等等...

关于java - 如何写入和读取同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478359/

相关文章:

方法中的Java小数点

java - 如何契约(Contract)卡布局

java - 使用 Spring 在后台运行进程的推荐方法是什么?

python - 重定向 sys.stdout 时 numpy savetxt 乱序

java - 将多行写入文件

c# - 有没有办法检查文件是否正在使用?

java - 转义 Java MessageFormat 的单引号

java - PoolableConnectionFactory 句柄无效

ASP.NET-使用 System.IO.File.Delete() 从 wwwroot 内的目录中删除文件?

C fread() 矩阵,无论矩阵大小如何,都读入九个错误值