4
votes

I am new in java and now learning the File io . but i am very confused about the io as there are many objects to deal with it (FileReader, FileWriter, BufferedReader, BufferedWriter, FileInputStream, FileOutputStream ... and may be there are more).

I want to know that what is the most efficient process for File io(What should i use ?).i don't want any encoding. i want just processing text files. Any simple example code will be greatly helpful.

Thank you.

3
You could try the different options... usually BufferedReader wrapping a FileReader is best - RNJ
Consider using the new IO API in java. NIO. - Eng.Fouad
i saw the NIO and found it a little heard (my bad !)(couldn't understand the codes) - palatok

3 Answers

8
votes

First important point to understand and remember:

  • Stream: sequence of bytes.

  • Reader/Writer: sequence of characters (Strings)

Don't mix them, don't translate for one to another if not necessary, and always specify the encoding.

Some quick recipes:

To read a file as a sequence of bytes (binary reading).

new FileInputStream(File f);

The same adding buffering:

new BufferedInputStream(new FileInputStream(File f));

To read a file as a sequence of characters (text reading).

new FileReader(File f); // ugly, dangerous, does not let us specify the encoding

new InputStreamReader(new FileInputStream(File f),Charset charset);  // good, though verbose

To add line-oriented buffering (to read lines of text)

new BufferedReader(  ... someReader ... );  

To output/write is practically the same (output/writer)

5
votes

Simple thumb of rule.

Text - Readers / Writers
Binary - InputStream / OutputStream

You can read more at Files

0
votes

Reading

Following will allow you to read line by line

BufferedReader br = new BufferedReader(new FileReader(fileLocationTxt));

Writing

Following will allow you to write line by line/part by part

DataOutputStream ds = new DataOutputStream(new FileOutputStream(newLocation));

As for your question, there is no BEST option. Even in here, you can see we have to use 2 or more at once (look at the constructors. They accept other reader/writer or inputStream/outputStream.

The best option depends on what you really want to do