2

标题几乎说明了一切。我读过几个人只是说你可以从文件中读取,但不能写入文件。

我曾尝试使用 getResourceAsStream 但它似乎对我不起作用。

通过代码可以很容易地理解我的程序;

在启动时,它从给定的文本文件中读取文本(如果不存在,则创建一个)。然后解析该字符串,并出现一个输入框以输入一个新数字。

然后将这些数字相加,并将结果写回文件中。

如果我需要先提取文本文件,写入它,然后以某种方式将其放回 jar 中,就这样吧,但我希望这是一个自动化过程,因此 jar 文件可以从它所在的任何地方运行如果它被移动,则不需要其他任何东西来复制它。

public static void main(String[] args) throws IOException {

    int iCount;
    int nCount;
    int fCount;
    String Count = "";
    String in;
    String workingDir = System.getProperty("user.dir");
    String file = workingDir + "\\File.txt";
    String[] dialog = {"Yes", "No"};
    String[] end = {"Restart", "Exit"};

        try { 

            BufferedReader readText = new BufferedReader(new FileReader(file));
            String input = readText.readLine();
            Count = input;

        } catch (FileNotFoundException e) {

        JOptionPane.showMessageDialog(null, "There is no file.");

        String fPre = "File";
        String fileName = fPre + ".txt";
        File f = new File(workingDir, fileName);
        f.createNewFile();
        BufferedWriter outputText = new BufferedWriter(new FileWriter(file));
        outputText.write("0");
        outputText.close();

        int selected = JOptionPane.showOptionDialog(null, "The file has been created for you. \n Do you wish to continue?", "Message", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, dialog, dialog[0]);

        if(selected == 0){
                Do.main(args); 
            } else { 
                System.exit(0); 
            } 

        }

    iCount = Integer.parseInt(Count);
    in = JOptionPane.showInputDialog("The current count is " + iCount + ". Please enter the new count amount.");
    nCount = Integer.parseInt(in);

    /* if(in == "[a-zA-Z]+" == true){
        in = JOptionPane.showInputDialog("The value entered is not a number. \n" + "Please enter a number.");
    } */

    fCount = iCount + nCount;

    try {
        BufferedWriter outputText = new BufferedWriter(new FileWriter(file));
        outputText.write(String.valueOf(fCount));
        outputText.close();
        JOptionPane.showMessageDialog(null, "New count is: " + fCount + ".");
        int selectedLast = JOptionPane.showOptionDialog(null, "Value has been written to file.\n" + "Do you wish to restart or exit?", "Confirm", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, end, end[0]);
        if(selectedLast == 0){
            Do.main(args);
        } else {
            System.exit(0);
        }   
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }   

}

我对 Java 很陌生,只学习了两个月,所以我不知道它的所有细节。

4

0 回答 0