Andrew Cameron Andrew Cameron - 1 year ago 40
Java Question

Appending text to an already existing file at a specific location

I am programming a game for a project and it is coming along smoothly but I have a slight problem, it uses a text file to save which achievements have been unlocked after the program closes, and I do not know how to edit it. While I could rewrite the entire thing using some checks to see what has been unlocked and then putting Y's in the rewrite using if else statements, and then replace it, this would take a large number of lines of code and not as reliable as on the spot writing the achievement, and probably be, although not that badly, more resource intensive, than to replace text at the desired line, into the text file.

so given this structure (number is attached to achievement, letter below tells my program whether it is unlocked or not, N means no Y means yes) if I unlocked achievement 2 for example, how would I search a text file that looks like this...

01
N
02
N
03
N
04
N
05
N
06
N
07
N
08
N
09
N
10
N
11
N
12
N


for 02 and then edit the line below from N to Y, using java 1.8 code. (the file is called Achievements.txt, and I have a variable called longPath that is the dynamic directory of where the game is stored, so for purposes of sample code the directory will work as

(longPath+"\\Achievements.txt")


ex.

Scanner scan = new Scanner(new File(longPath+"\\Achievements.txt"));


is the start of the code I use to determine in the code which achievements are unlocked (the scanner code is working just fine btw)

edit: rewriting the file is not very feasable, and i am going to bed now, so i will respond tomorrow morning at ~8:10 Estern Time

Answer Source

If you are simply replacing N with Y i.e. not writing extra information then RandomAccesFile should work for you

see this link for an example of writeChars

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download