JavaCore IOStream byte stream

Classification of streams:

By direction: input stream output stream

According to the unit: byte stream character stream

By function: node stream filter stream (package stream, process stream)

InputStream is the unified parent class of all byte input streams. Abstract class

int read();

int read(byte[] data) *****

int ream(byte[] data, int off, int len)

OutputStream The unified parent class of all byte output streams Abstract class

write(int data);

write(byte[] data)

write(byte[] data, int off, int len) *****

FileInputStream input stream byte stream node stream

FileOutputStream output stream byte stream node stream

*: They are all node streams. The constructor allows passing in File objects/String paths

*: Although they are all node streams, they can only connect files, not directories

Otherwise, an exception FileNotFoundException (Access Denied) occurs directly

*:FileInputStream is most commonly used read(byte[] data)

*:FileOutputStream most commonly used is write(byte[] data,int,int)

*:FileInputStream uses -1 as the sign of the end of reading

*:FileOutputStream is the node output stream

When the node output stream creates an object, if the connected file does not exist, it will be created automatically at the moment the stream is created. There is no need to build it manually. In fact, the File class has a method called createNewFile(), but if the connected directory structure does not exist An exception will occur directly, so the File class has a method called mkdis()

*:FileOutputStream is the node output stream

The node output stream is extremely destructive. If the connected file already exists when the object is created, it will be directly replaced by a new blank file at the moment the stream is created. If our requirement is to append and connect new content after the original content You can pass parameters to the construction method to specify the append mode to open new FileOutputStream(“abc.txt”,true);

*: You must be proficient in standard try catch and TWR exception handling

import java.io.*;
public class TestFileInputStream{
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("abc.txt");
byte[] data = new byte[3];
int len;
while((len = fis.read(data))!=-1){
for(int i = 0;i<len;i ++ ){
System.out.print((char)data[i]);
}
}
fis. close();
}
}
import java.io.*;
//TWR => Try-With-Resources => try catch syntax with resource control
// since JDK7.0
public class FileCopyWithTWR{
public static void main(String[] args) throws Exception{
try(FileInputStream fis = new FileInputStream("1.mp3");
FileOutputStream fos = new FileOutputStream("3.mp3");){

byte[] data = new byte[5<<20];
int len;
while((len = fis.read(data))!=-1){
fos.write(data,0,len);
}
}catch(Exception e){
e.printStackTrace();
}
}
}

BufferedInputStream byte stream input stream filter stream

BufferedOutputStream byte stream output stream filter stream

*: They are used as filter streams to add buffer space to the original stream, thereby improving the throughput of each read and write, thereby improving efficiency

*: They are filter streams, they cannot be directly connected to files, they can only be connected to other streams

*: The second parameter of their construction method allows specifying the size of the buffer space, the default is 8192, which is 8k

*: The most commonly used read() of BufferedInputStream

*: BufferedOutputStream most commonly used write(int data)

*: BufferedInputStream also uses -1 as the sign of the end of reading

*: BufferedOutputStream is a buffered output stream. When using a buffered output stream, be sure to clear the buffer in time to prevent data from staying in the buffer space and causing loss

Under what circumstances will the buffer be emptied

1. Automatically empty when full, no operation required

2. The operation of closing the stream will trigger the emptying of the buffer

3. Actively call the method flush() to clear the buffer;

import java.io.*;

public class TestBufferedStreamWithTWR{
public static void main(String[] args) throws Exception{
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("1.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("3.mp3"))){

int data;
while((data = bis.read())!=-1){
bos. write(data);
}

}catch(Exception e){
e.printStackTrace();
}
}
}

DataInputStream byte stream input stream filter stream

DataOutputStream byte stream output stream filter stream

*: As filter streams, add the function of reading and writing basic data types to the original stream

*: As filter streams, they cannot be directly connected to files and can only be connected to other streams

boolean char byte short int long float double

*: The core method readXxxx() provided by DataInputStream has a return value

*: The core method writeXxxx() provided by DataOutputStream requires parameters

*: DataInputStream can no longer use -1 as the end of reading. If you continue to try to read once the end of the file is reached, EOF (EndOfFile) Exception will be triggered directly.

import java.io.*;
public class TestDataStream{
public static void main(String[] args) throws Exception{
/*
int level = 685;

//archive
DataOutputStream dos = new DataOutputStream(new FileOutputStream("save.data"));
dos. writeInt(level);
dos. close();
*/

//read file
DataInputStream dis = new DataInputStream(new FileInputStream("save.data"));
int x = dis. readInt();
dis. close();
System.out.println(x);
}
}

ObjectInputStream byte stream input stream filter stream

ObjectOutputStream byte stream output stream filter stream

*: They are used as filter streams to add the function of reading and writing objects to the original stream

*: As filter streams, they cannot be directly connected to files and can only be connected to other streams

*: The core method readObject() provided by ObjectInputStream

*: The core method writeObject() provided by ObjectInputStream

*: ObjectInputStream also cannot use -1 as the end of reading, but once it reaches the end of the file and continues to try to read, EOFException will be triggered

*: If you want to persist, you need to serialize first

The type of the object to be saved to disk must implement the Serializable interface implements Serializable If the type to be persisted has other reference type properties, even the type of these properties must implement the Serializable interface If some properties are irrelevant If you need to participate in persistence, you can use transient to modify transient -> transient does not participate in persistence

*: If a collection object is persisted, the element type in the collection must also implement the serialization interface. If the persistence is a TreeSet or TreeMap that uses a comparator, even the type of the comparator must implement the serialization interface. Because the comparator is a property of TreeSet or TreeMap

import java.io.*;
import java.text.*;
public class ExecObjectStream{
public static void main(String[] args){
Wish myWish = new Wish("May the world be peaceful","5v");

try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("wish.data"))){
oos.writeObject(myWish);
}catch(Exception e){
e.printStackTrace();
}

try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("wish.data"))){
Object obj = ois. readObject();
System.out.println(obj);
}catch(Exception e){
e.printStackTrace();
}
}
}
class Wish implements Serializable{
String content;//The content of the wish
String name;
long time;
public Wish(String content,String name){
this. content = content;
this.name = name;
time = System. currentTimeMillis();
}
@Override
public String toString(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String ok = sdf. format(time);
return content + "\\
\t\t\t" + name + "\\
\t\t\t" + ok;
}
}

Two abstract parent classes:
InputStream is the unified parent class of all byte input streams. Abstract class
int read()
int read(byte[] data) *****
int read(byte[] data, int off, int len)
OutputStream The unified parent class of all byte output streams Abstract class
write(int data)
write(byte[] data)
write(byte[] data, int off, int len) *****

Two node streams:
FileInputStream read(byte[] data)
FileOutputStream write(byte[],int,int)

Six filter streams:
BufferedInputStream adds buffer space to improve reading efficiency
read();
BufferedOutputStream adds buffer space to improve writing efficiency
write(int data);
DataInputStream adds the ability to read primitive data types
readXxxx();
DataOutputStream adds the ability to write out primitive data types
writeXxxx();
ObjectInputStream adds functionality to read objects
readObject();
ObjectOutputStream adds the ability to write out objects
writeObject();

*: When copying files, if the target file becomes larger than the source file, usually why?
write() without taking three arguments
Not paying attention to how many bytes are actually read this time but
Write out the entire array directly

*: When copying files, if the destination file becomes smaller than the source file, usually why?
A buffered output stream was used but the buffer was not cleared in time
The last set of data is stuck in the buffer space

*: Under what circumstances will the buffer be cleared:
1. Automatically empty when full, no operation required
2. The operation of closing the stream will trigger the emptying of the buffer
3. Actively call flush();

*: EOFException => End Of File
Using DataInputStream and ObjectInputStream
At the time, the stream cannot be marked with -1 as the end of reading
Once the end-of-file has been reached, keep trying to read
will directly trigger the exception

/*
Please find all .jpg pictures in c:\【Include subdirectories】
And copy it to the d:\foto directory [d:\foto directory does not exist yet]
Let the filenames be named according to the serial number
00001.jpg
00002.jpg
00003.jpg
.....
*/
import java.io.*;
public class BigOneAG{
public static void main(String[] args){
createTarget();
kill(new File("c:\"));

}
//A method dedicated to creating the target directory
public static void createTarget(){
File dir = new File("d:\foto");
if(!dir. exists()){
dir.mkdirs();
}
}
//A method dedicated to getting the next file name
static int id;
public static String nextName(){
StringBuffer buff = new StringBuffer(String. valueOf( + + id));
while(buff. length() < 5){
buff.insert(0,"0");
}
buff.append(".jpg");
return buff.toString();
}

//A method to copy files
public static void copy(File src,File tar){
try(FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(tar)){
byte[] data = new byte[32768];
int len;
while((len = fis.read(data))!=-1){
fos.write(data,0,len);
}
}catch(Exception e){
e.printStackTrace();
}
}

public static void kill(File tar){
File[] ds = tar.listFiles((x) -> x.isDirectory());
File[] js = tar.listFiles((x) -> x.isFile() & amp; & amp; x.getName().toLowerCase().endsWith(".jpg"));
if(ds == null) return;
for(File d : ds){
kill(d);
}
for(File j : js){
String name = nextName();
File t = new File("d:\foto",name);
copy(j,t);
}
}
}

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge algorithm skill treehomepage overview 41872 people are studying systematically