Write only one line in Bufferedwriter

Asked

Viewed 410 times

1

Well, I have a text file with a few lines, for you to understand better, here’s 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, but when I put the code:

bw.write("1");    

It erases all the contents of my file and leaves only this 1 empty, there is some way that change only a few lines, not only the first, but others too, in case I have to change some other line in the future?

Full line recording for you to see how I did:

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

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("1");
    bw.close();

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 class RandomAcessFile has everything you need to browse 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 plan to modify the file size (e.g., replace one line with a larger or smaller one) it may be easier to rewrite the entire file than to try to manipulate it.


If you want to use something new, the NIO.2 API introduced the SeekableByteChannel with similar positioning features. You can find an example in Oracle’s Official Tutorial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.