标题几乎说明了一切。我读过几个人,只是说你可以从文件中读取,但不能写入。
我尝试过使用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很新,只学了两个月,所以我不知道它的所有细节。