Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best File I/O option in java?

Tags:

java

file

file-io

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.

like image 403
palatok Avatar asked Dec 11 '22 19:12

palatok


2 Answers

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)

like image 150
leonbloy Avatar answered Dec 14 '22 07:12

leonbloy


Simple thumb of rule.

Text - Readers / Writers
Binary - InputStream / OutputStream

You can read more at Files

like image 41
muruga Avatar answered Dec 14 '22 08:12

muruga