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?

4
  • Never have empty catch statements. Who knows what exceptions you are missing. Please add an e.printStacktrace() and check nothing is printed. Commented Dec 23, 2013 at 15:34
  • I add it, but problem is not here Commented Dec 23, 2013 at 15:45
  • What does super(l) do? Which class is the parent class? Where are you calling saveFile() ? And why are you writing back the same file, and not to a separate file? Commented Dec 23, 2013 at 15:57
  • 1
    Hi Did you manage to resolve this issue ? Commented Nov 2, 2019 at 2:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.