簡體   English   中英

關閉並重新啟動可執行文件后,無法修改或刪除由 my.jar 可執行文件創建的文本文件

[英]Unable to modify or delete text file created by my .jar executable after closing and relaunching the executable

我有一個相當簡單的 Java 項目,該項目在當前目錄(在我的Documents文件夾中的某個位置)中打開(如果不存在則創建)一個文本文件,使用BufferedReader讀取數據,然后使用PrintWriter進行修改。 該代碼在Eclipse中運行良好。 但是,當導出到runnable.jar文件時,生成的.jar 可執行文件只能修改它自己創建的文件(因為它以前不存在而創建)。 如果我然后關閉並重新啟動.jar 作為新實例來修改它在上次啟動時創建的文件,我得到

java.io.FileNotFoundException: Data.txt (Access is denied) at java.base/java.io.FileOutputStream.open0(Native Method) at java.base/java.io.FileOutputStream.open(FileOutputStream.java:293) at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235) at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184) at java.base/java.io.PrintWriter.<init>(PrintWriter.java:309) at project.file.LocalStorageFile.setList(LocalStorageFile.java:136)...

所以重申:

  1. 在 eclipse 中運行 - 工作正常
  2. 導出到可運行 jar
  3. 運行jar
  4. 如果文件不存在,它會創建一個
  5. 讀取文件
  6. 如果它在步驟 4 中創建了文件 - 寫入成功,但如果文件已經存在 - 異常

在調查此異常時,答案建議:

  • 磁盤 C 上的受限目錄(這對我來說不可能,因為我的文件夾是 Documents 中一個完全可訪問(至少一次)的文件夾,並且該文件夾的權限似乎是有序的)
  • 忘記關閉流(我在 finally 塊中關閉了讀取器和寫入器流,並確保它們已使用一些控制台打印行關閉)
  • 正在使用文件(在計算機重新啟動后問題仍然存在,即使在我之前必須重新安裝操作系統之后)
  • 缺乏管理員權限(我以管理員身份啟動了 CMD 並將其用於“java -jar project.jar”,結果相同)
  • 嘗試使用等於 false 的 file.delete() 刪除文件
  • 嘗試沖洗打印作家
  • 嘗試使用 file.setReadable(true) 和 file.setWritable(true) 將文件設置為可讀可寫

我正在使用gradle來構建 my.jar 因為我需要一些從那里獲得的庫以用於其他功能。 但即使我使用 Eclipse 本身“導出為可運行的 jar”,我也會遇到同樣的問題。 當然,當我直接從 Eclipse 多次運行程序時,訪問和修改同一個文件沒有問題。

這是我的 LocalStorageFile class 如果你想在你的機器上測試它的讀寫功能:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TreeMap;

/**
 * Store keywords and strings in a local file.
 * 
 * Format: keyword1, keyword2 \t string1 \n keyword3, keyword4 \t string2
 * \n
 */
public class LocalStorageFile {
    private static final String FILE_PATH = "Data.txt"; // current directory
    private static final String KEY_SEP = "\t"; // key/value separator
    private static final String LINE_SEP = "\n"; // line separator

    private static File file;

    public LocalStorageFile() {
        file = new File(FILE_PATH);

        // Create file if it doesn't exist
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Retrieve list from file "Data.txt" in local directory.
     * 
     * @return TreeMap of keys and strings.
     */
    public static TreeMap<String, String> getList() {
        System.out.println("Retrieving list data.");
        TreeMap<String, String> myList = new TreeMap<String, String>();

        File file = new File(FILE_PATH);
        if (!file.exists()) {
            try {
                file.createNewFile(); // if file already exists will do nothing
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        BufferedReader br = null;
        // Read file line by line and add to myList
        try {
            file.setReadable(true);
            file.setWritable(true);
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("  Now reading line:" + line);
                String[] keyValuePair = line.split(KEY_SEP);
                if (keyValuePair.length == 2) { // avoid any error lines
                    // Re-insert tabs and newlines
                    String key = keyValuePair[0].replaceAll("\\\\t", "\t")
                            .replaceAll("\\\\n", "\n");
                    String value = keyValuePair[1].replaceAll("\\\\t", "\t")
                            .replaceAll("\\\\n", "\n");
                    // Put data into map
                    myList.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                    System.out.println("Buffered reader closed.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return myList;
    }

    /**
     * Rewrite list to file "Data.txt" in local directory.
     * 
     * @param myList
     *            TreeMap of keys and strings.
     * @return 1 on success, 0 on fail.
     */
    public static int setList(TreeMap<String, String> myList) {
        System.out.println("Saving list data.");
        String textData = "";
        int result = 0;

        // Construct textData using myList
        for (String key : myList.keySet()) {
            String value = myList.get(key);

            // Sanitize strings
            String keyClean = key.replaceAll("\t", "\\\\t").replaceAll("\n",
                    "\\\\n");
            String valueClean = value.replaceAll("\t", "\\\\t").replaceAll(
                    "\n", "\\\\n");

            // Assemble line with separators
            String line = keyClean + KEY_SEP + valueClean + LINE_SEP;

            System.out.println("  Now saving line:" + line);
            textData += line;
        }

        // Replace file content with textData
        PrintWriter prw = null;
        File file = new File(FILE_PATH);
        if (file.exists()) {
            boolean delStatus = file.delete();
            System.out.println("File deleted? " + delStatus);
            // file.setReadable(true);
            // file.setWritable(true);
        } else {
            System.out.println("File doesn't exist");
        }
        try {
            file.createNewFile();

            prw = new PrintWriter(file); // <- this is line 136 from the exception
            prw.println(textData);
            prw.flush();
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (prw != null) {
                prw.close();
                System.out.println("Print writer closed.");
            }
        }
        return result;
    }

}

代碼似乎沒有問題,但可能是我的系統有問題?

任何關於我應該在哪里挖掘的線索將不勝感激。

好的。 我終於讓它工作了。 我不得不暫時關閉我的 Avast Antivirus,並且能夠編輯現有文件。 特別是“勒索軟件保護”正在保護我的 Documents 文件夾。

感謝評論者的幫助,沒有您,我們無法得出這個結論! 這個問題的答案提到 Comodo 防病毒軟件會導致同樣的問題。 我將在未受保護的文件夾中創建一個新的工作目錄,因為 Avast 不允許我添加非 exe 文件作為例外。

暫無
暫無

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

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