Title pretty much says it all. I've read several people just saying you can Read from the file, but not Write to it.
I have tried using getResourceAsStream but it never seems to work for me.
My program can be understood fairly easily through the code;
At startup it reads text from the given text file (or creates one if it isn't there). This string is then parsed, and an input box comes up to enter a new number.
These numbers are then added, and the result written back into the file.
If I need to extract the text file first, write to it, then somehow place it back into the jar, so be it, but I want this to be an automated process, so the jar file can be run from wherever it is and it won't need anything else to be copied with it if it is moved.
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();
}
}
I'm fairly new to Java, having only been learning it for two months, so I'm not aware of all of its ins and outs.