I am pretty new to java but I have been working on a few projects recently.
The most recent ive been having trouble with. I am running a GUI, and within this GUI I am reading in information from a certain file. My problem is that I want to write the information from certain textfields in the GUI into that same file. Some of these textfields need to change what is already there too. However the only method i am aware of is to create a new FileWriter and so on ie:
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
How do I append or change information in the file, without recreating the file, and thus losing all the info?
i think you've to think about random access files (RandomAccessFile) with such files you can open a stream on a native file for reading and writing at the same time. but you have to be aware of where you are writing inorder not to write in an existing data.
open for just reading: RandomAccessFile f= new RandomAccessFile("filename.txt","r");
open for reading and writing : RandomAccessFile f= new RandomAccessFile("filename.txt","rw");
Thank you very much for your quick reply. I understnad this, i was just wondering how i would now use the RandomAcessFile to edit specific strings, floats etc in a file. could u give me an example perhaps?
you can use the following examples after you've opened the file for writing with the statement: RandomAccessFile f=new RandomAccessFile("Mary.txt","rw");
you can write to file using : f.writeInt(intVal); f.writeChars( charArray[]0; f.writeDouble(doubleVal); and you can move between bytes using f.seek(numberOfBytes); and after you finished you have to close the stream by the statement f.close(); and you can open it agin for reading by statement : RandomAccessFile f=new RandomAccessFile("Mary.txt","r");