Originally posted by Salamina Daniel:
A file is going to be read one line at a time into String objects. Which construction is most suitable for reading the file ?
1. FileInputStream in=new FileInputStream("file.name");
2. DataInputStream in=new DataInputStream(new FileInputStream("file.name"));
3. DataInputStream in= new DataInputStream(new FileInputStream("file.name","r"));
4. BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("file.name")));
5. BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("file.name"),"8859_1"));
I believe the answer should be (2.) as DataInputStream has a readUTF()method that returns a String.
Answer 1 - wrong because FileInputStream reads bytes (low-level input stream)
Answer 3 - wrong construction- related to RandomAccessFile(File file, String mode) not FileInputStream
Answer 4 - wrong - BufferedReader read data as chars (StringReader read data as Strings)
Answer 5 - wrong - same as 4 but specify an encoding construction
But in the answer it is mentioned that we shoul read one line at a time so I think we can do the job with a LineNumberReader -readLine() return String so the answer 4 could be correct if we chain like this:
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream("file.name")));
LineNumberReader l= new LineNumberReader(in);
So what is the correct answer ?
Originally posted by Valentin Crettaz:
Hi guys,
I'd just like to remember you one thing, the questions says "A file is going to be read [b]one line at a time..." So the only correct answer can be either 4 or 5 since readUTF of DataInputStream only returns a String object and not a whole line. BufferedReader has a readLine method which can achieve what is asked. Now, we have to choose between 4 and 5 and it's not very difficult since the encoding 8859_1 does not exist (ISO-8859-1 does though)
So the correct answer should be 4.
Note: LineNumberReader is a subclass of BufferedReader... The solution you gave is correct but not necessary since BufferedReader already provides all constructs necessary to fulfill what is asked...
HIH
[/B]
Originally posted by Valentin Crettaz:
Hi Ragu,
Again the question says "Which construction is [b]most suitable for reading the file ?"
As you pointed out readLine in DataInputStream is deprecated and there is a note in the API stating that a preferred way is to use BufferedReader.readLine().
Again, the most suitable choice here in this very question is 4 and not 2, do you agree ? I mean there is no other choice if you want to fully comply with the wording of the question.
[/B]
Originally posted by Ragu Sivaraman:
As long as your are here in javaranch, I always feel I will
get a correct response :-)
Have fun
Ragu
/jan
Whatever you say buddy! And I believe this tiny ad too:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
|