Personally, the stream is the medium in which data is exchanged between different devices in Java, such as the transmission of data in the socket, and the read and write operations of the files, all of which are implemented through streams.
Type of flow
From the processing data type, the stream is mainly divided into character stream (InputStream, outputstream) and byte stream (Reader, Writer), and from the functional point of view, it is mainly divided into input stream and output stream.
Read and write files
File file =newFile(".\\test.txt");
//参数true:表示在文件后边追加内容
FileOutputStream fileOutputStream =newFileOutputStream(file,true);
FileInputStream fileInputStream =newFileInputStream(file);
//装饰者模式,使用带缓冲的输入流
BufferedInputStream bufferedInputStream =newBufferedInputStream(fileInputStream);
//使用byte,字节流读取文件中的内容
byte[]b =newbyte[100];
bufferedInputStream.read(b);
Stringstring=newString(b,"UTF-8");
System.out.println(string);
//使用字符流读取文件中的内容
BufferedReader bufferedReader =newBufferedReader(inputStreamReader);
System.out.println(bufferedReader.readLine());
//写入文件
OutputStreamWriter outputStreamWriter =newOutputStreamWriter(fileOutputStream);
outputStreamWriter.write("jjjjjjjjjjjjjjjjjjjd我们哈哈哈哈哈");
BufferedOutputStream bufferedOutputStream =newBufferedOutputStream(fileOutputStream);
bufferedOutputStream.flush();
Stringstring="我们进顶顶顶顶顶顶顶顶顶大大大";
byte[]b =string.getBytes("UTF8");
bufferedOutputStream.write(b);
bufferedOutputStream.close();
Socket using Server
publicclassTcpServer{
publicstaticvoid main(String[] args)throwsIOException{
// TODO Auto-generated method stub
String getString;
String sendString;
ServerSocket socket =newServerSocket(6789);
while(true){
Socket connection = socket.accept();
BufferedReader reader =newBufferedReader(newInputStreamReader(connection.getInputStream()));
DataOutputStream outputStream =newDataOutputStream(connection.getOutputStream());
getString = reader.readLine();
sendString = getString.toUpperCase()+"\n";
outputStream.writeBytes(sendString);
}
}
}
Client
publicclassTcpClient{
publicstaticvoid main(String[] args)throwsUnknownHostException,IOException{
String sendString;
String getString;
System.out.println("start connection");
Socket socket =newSocket("127.0.0.1",6789);
System.out.println("connect successfully");
DataOutputStream outputStream =newDataOutputStream(socket.getOutputStream());
BufferedReader fromServer =newBufferedReader(newInputStreamReader(socket.getInputStream()));
sendString ="send to server from tcpclient";
outputStream.writeBytes(sendString +"\n");
getString = fromServer.readLine();
InputStreamin= socket.getInputStream();
byte[] b =newbyte[100];
in.read(b);
Stringstring=newString(b,"UTF-8");
System.out.println(b);
socket.close();
}
}
From for notes (Wiz)
About the use of Java streaming--Files and sockets