Write only one row in BufferedWriter

1

Well, I have a text file with a few lines, for you to understand better, here is what I have in this file:

0    
Zombie+160+-50    
Zombie+160+290    
Robot+-50+120    
Spider+370+120    
doors    
1+BossRoom1    
3+Loja1    
Basically, I want to change that 0 to 1 while the program runs, what I did then is to use a BufferedWriter and a FileWriter, however when I put the code:

bw.write("1");    

It deletes all the contents of my file and leaves only 1 in the blank, is there any way I can change only a few lines, not only the first but also others, in case I have to change some other line in the future? p>

Complete recording line for you to see how I did it:

File file = new File("resources/Save/Room1.txt");

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("1");
    bw.close();
    
asked by anonymous 22.01.2015 / 22:24

1 answer

3

You need a RandomAccessFile .

File file = new File("resources/Save/Room1.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0l);
raf.writeChars("1");
// Não se esqueça de tratar exceções, fechar recursos, etc

The RandomAcessFile class has everything you need to navigate within a file, as well as read and manipulate parts of it (either binary or textual). More details can be found in Javadoc.

Keep in mind however that if you intend to modify the file size (eg, replacing a line with a larger or smaller line) it may be easier to rewrite the entire file than to try to manipulate it.

If you'd like to use something newer, the NIO.2 API introduced SeekableByteChannel " with similar positioning features. You can find an example in Oracle's Official Tutorial .

    
22.01.2015 / 22:43