Tuesday, March 25, 2014

Java IO Tutorial - file read / write

Commonly Used Methods for Small Files

Reading All Bytes or Lines from a File

If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method:

Path file = ...;
byte[] fileArray;
fileArray = Files.readAllBytes(file);

Writing All Bytes or Lines to a File

The following code snippet shows how to use a write method.

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);


Original tutorial is locate here: http://docs.oracle.com/javase/tutorial/essential/io/file.html

No comments:

Post a Comment