簡體   English   中英

如何寫入和讀取同一文件

[英]How to write to and read from the same file

我當前的問題是我想寫入和讀取文件,但是,我一直試圖引發異常並實例化變量,只是為了不斷獲取有關聲明為“無法實例化”的變量的錯誤。 我不確定如何解決此問題。

我試過使用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可能尚未初始化。”

有誰知道如何解決這個問題?

“變量fw可能尚未初始化。”

您需要更仔細地查看您的代碼。 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){

    }

等等...

只需將變量fw初始化為null即可解決“變量fw可能尚未初始化”錯誤!

FileWriter fw = null; 是正確的。

-謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM