• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which is the best way to write and read from a file  RSS feed

 
Gaurav Chikara
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to write some names to a file which i want to retrieve later in my program for searching purpose
I tried using RandomaccessFile but there we have writechars()
for writing as a string and readLine for reading
but the problem is that even if i enter two strings
and while reading i want to read them one by one
it is not done rather it concatenates two strings and shows as one
eg.
i wrote
fr.writeChars("Hello");
fr.writeChars("Doctor");
and when i tried to read them
rf.readLine()
it gave
H e l l o D o c t o r
as output
Now how can i retrive the strings one by one
i m really confused
 
Matt Siegel
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Give this a try:
Write to the file using FileWriter, and then read in from the file using FileReader.
// Write to file
FileWriter out = new FileWriter("my.file");
out.write("Hello\n");
out.write("Doctor\n");
out.close();
// Read from file
BufferedReader in = new BufferedReader(new FileReader("my.file"));
String hi = in.readLine();
String doc = in.readLine();
in.close();
Of course the reads will be in a loop.
Hope this helps!
Matt
[This message has been edited by Matt Siegel (edited March 15, 2001).]
[This message has been edited by Matt Siegel (edited March 15, 2001).]
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are still wondering why RandomAccessFile failed you, its because you wrote the two Strings to the same line. You need to write a line separator manually. Avoid hard-coding the line separator like Matt did (that final "\n") Line separators are platform dependent. Either use System.getProperty("line.separator") to get the line separator or use BufferedWriter or PrintWriter, both of which have methods to write the platform-dependent line separator.
 
sidharth nayak
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think the problem with u was that of using a chracter stream reader
due to which the spaces originate in the middle

try usin ga byte stream reader
 
Gaurav Chikara
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys for replying after a span of 3 years when I myself have forgotten that I faced such kind of problem
Thats why it is called
"Better late than never"
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And did you reach the doctor?
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!