First type: byte stream fileinputstream FileOutputStream
1.1 Read operations
//first create a stream connected to the hard drive (a channel to drive and memory)
new fileinputstream ("D:\\demo.txt");
//Create buffer size is 1k
byte[] bytes = new byte[ [1024x768];
int data = 0;//Storage of valid bytes
stringbuffer sb = New StringBuffer ();
//because the file size is usually much larger than the buffer size, you want to iterate
while (( data = Fis.read (bytes)) =-1) {//Return-1 The file is read, stop looping
string Temp=new string ( Bytes,0,data);//reads the number of bytes in the buffer, converts it to a string
System.out.printlb ("= = Valid bytes = = = =" +data);
}
System.out.printlb (sb.tostring ());
Close Stream
Fis.close ();
1.2 Write operations
Create a stream that reads a file
New FileOutputStream ("E:\\demo.txt");
String temp = "Sea memory confidant, near the horizon." ";
Break the string into bytes and fill in the byte array
Writes to the specified path, no file is created
Fos.write (bytes);
Close the stream
Fos.close ();
System.out.println ("Write succeeded! ");
Second type: Character stream char FileReader FileWriter
Tips: The relationship between Char and byte is not fixed under different operating systems and encoding methods
Generally considered: gbk/gb2312 2 byte
Utf-8 of 3 byte
2.1 Read operations
New FileReader ("E:\\demo.txt"); Char New Char [1024x768new stringbuffer (); int length = fr.read (CH); while (Length! =-1 = fr.read ();} System.out.println (Sbf.tostring ()); Fr.close ();
2.2 Write operations
New FileWriter ("D:\\demo.txt");
Fr.write ("The joy of having friends from afar");
Fr.close ();
Third type: Character reading and writing scheme with buffer
BufferedReader
BufferedWriter buffer The amount of data stored by default is 1024byte
3.1 Read operations
Reader FR = new FileReader ("D:\\demo.txt");
BufferedReader br = new BufferedReader (FR);
String line = Br.readline ();
while (line! = null) {
System.out.println (line);
line = Br.readline ();
}
Br.close ();
Fw.close ();
3.2 Write operations
Writer FW = new FileWriter ("D:\\demo.txt", true);//true is a continuous append
BufferedWriter bw = new BufferedWriter (FW);
Bw.write ("Learning and time learning, not also said");
Bw.close ();
Fw.close ();
Fourth: Binary mode read and write scheme
DataInputStream
DataOutputStream
Read and write operations: copy and paste
InputStream is = new FileInputStream ("e:\\ spring. jpg");
DataInputStream dis = new DataInputStream (IS);
OutputStream Ops = new FileOutputStream ("d:\\ spring. jpg");
DataOutputStream dos = new DataOutputStream (OPS);
byte[] bytes = new byte[1024];
int date = 0;
while ((date = Dis.read (bytes))! =-1) {
Dos.write (bytes,0,date);
}
Dos.close ();
Ops.close ();
Dis.close ();
Is.close ();
System.out.println ("copy succeeded");
Four ways to read Java file IO write