0

I have a text file with this content:

Ehsan,12345,11111,1000
maryam,147258,222,5000
reza,758694,abcd,4600
Ali,564789,kfcg,7500
mohammad,658932,bnfgd,5800
zahra,758964,798564,6750
rasool,568974,457832,1400
Ahmad,785403,wasd,6900
Amir,3205809,man123,7000
Morad,1,1,8900

I read all line of it with RandomAccessFile:

Account2[] members = new Account2[10];
try {
  RandomAccessFile raf = new RandomAccessFile("d:\\myTxtFile.txt", "r");
  raf.seek(0);
  long position = raf.getFilePointer();
  int counter = 0;
  while(raf.length()> position){
    members[counter] = new Account2(raf.readLine(), position);
    position =raf.getFilePointer();
    counter++;
  }
} catch (Exception e) {
     e.printStackTrace();
}

Then in Account2 I have a method to save file after changes:

private long position;
public Account2(String l, long p){
  super(l); 
  position = p;
}
public void saveFile(){
  try {
    RandomAccessFile raf = new RandomAccessFile("d:\\myTxtFile.txt", "rw");
    raf.seek(position);
    String newContents = "my new contents here";
    //raf.writeChars(newContents.toString());
    raf.writeUTF(newContents);
  } catch (Exception e) {
     e.printStackTrace();
  }

But it destroy my text file and add some strange character in head of line and bring next line to tail of line. Why is this?

Ehsan
  • 2,165
  • 7
  • 32
  • 66

1 Answers1

1

To answer your question: raf.writeUTF(newContents); is "destroying your file" and causing the "strange characters" to appear. Instead u wanna use raf.writeBytes(newContents);

Furthermore I don't know what this code should accomplish but consider that u can't use a RandomAcessFile to insert a string at a specified position. Instead your saveFile() method overwrites the beginning of every line with "my new contents here". If both the old and the new String have the same length this is not a problem but apart from that this messes up your file too. To prevent that rewrite your file with the new contents. E.g. java replace specific string in textfile

Community
  • 1
  • 1
user3608078
  • 158
  • 1
  • 8