Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Various IO methods

 
Vinod Kumar
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Considering these questions,how one can make sure he is making a correct choice from the available answers for the scenario asked?
Questions:
What is the most appropriate method for read a line from a file and to store it in a String object?
I have a socket handle s. I want to read data a line at a time from the remote network using this socket handle. what is the most appropriate choice
I can use?
Regards,
Vinod
 
Peter Bugla
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vinod Pai:

Questions:
What is the most appropriate method for read a line from a file and to store it in a String object?
I have a socket handle s. I want to read data a line at a time from the remote network using this socket handle. what is the most appropriate choice
I can use?

File and socket, doesn't match, so the question doesn't make sense. If we leave out "File", you can try thinking it through like this:
First thing, look at what you have.
That's a Socket here. The only usable thing it offers is an InputStream:
s.getInputStream()
If you want to read data "a line at a time" we're
talking about characters, so it would be nice to use some XxxxReader. This Reader should be able to work with what we have (InputStream), so why not have a look at InputStreamReader:
new InputStreamReader(s.getInputStream())
We want to read "a line" (at a time), probably more than one altogether.
We can of course write some loop reading character and check for some line-ending characters, but perhaps we can avoid this by using some Buffering stuff ... BufferedReader fortunately offers a method readLine giving back a String :-)
BufferedReader b = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = b.readLine();
� voil� :-)
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good explanation Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic