Original address: http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html
[Java] Read file method encyclopedia 1, read the contents of the file by byte 2, read the contents of the file by character 3, read the contents of the file by line 4, Random read the contents of the file
public class ReadFromFile {/**
* 1, read files in bytes, often used to read binary files, such as pictures, sounds, images and other documents.
*/
public static void Readfilebybytes (String fileName) {
File File = new file (fileName);
InputStream in = null;
try {
System.out.println (reads the contents of the file in bytes, one byte at a time: ");
Read one byte at a time
in = new FileInputStream (file);
int tempbyte;
while ((Tempbyte = In.read ())!=-1) {
System.out.write (Tempbyte);
}
In.close ();
catch (IOException e) {
E.printstacktrace ();
return;
}
try {
SYSTEM.OUT.PRINTLN (Read the contents of the file in bytes, read multiple bytes at a time: ");
Read multiple bytes at a time
byte [] tempbytes = new byte [100];
int byteread = 0;
in = new FileInputStream (fileName);
Readfromfile.showavailablebytes (in);
Reads multiple bytes into a byte array, byteread the number of bytes read at a time
while ((Byteread = In.read (tempbytes))!=-1) {
System.out.write (tempbytes, 0, Byteread);
}
catch (Exception E1) {
E1.printstacktrace ();
finally {
if (in!= null) {
try {
In.close ();