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 を始めて 2 か月しか経っていないので、Java の詳細をすべて把握しているわけではありません。

4

0 に答える 0