• Post Reply Bookmark Topic Watch Topic
  • New Topic

FilesWithStringBuffer

 
Ramesh Pappala
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I read the contents of a file and assigned them to a string object.
But, the newline character in the file will be added to that string object content. How to replace that newline character in the string object.

I used replace method of String class. but it's not working.

/* This is my code */

RandomAccessFile raf=new RandomAccessFile("C:\\Documents and
Settings/mss222/Desktop/IO/Status2.txt","r");
int len=(int)raf.length();
byte[] fileInData=new byte[len];
raf.read(fileInData);
String fileData=new String(fileInData);
fileData.replace('\n',' ');

// But when iam printing that string object, it's coming just like previous file. How to change that newline character in the file with another character.

Please send me a sample code or a suggestion for this.

Thank you,
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume your input file is a text file. What is your goal, what are you trying to do with this file? There may be easier ways to do what you're trying to do than to read in the file, in its entirety, with a RandomAccessFile, if we only knew what you were intending to do with the contents of the file.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not disagreeing with Jeff, just pointing out an important error in the code you've written: String.replace(), like all other String methods that appears to modify a String, actually returns a new modified String, leaving the original unchanged; you need to say something like

fileData = fileData.replace('\n',' ');
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!