个人感觉,流是java中不同设备之间交换数据的媒介,例如socket中数据的传输,以及文件的读写操作等,都是通过流来实现的.
流的种类
从处理的数据类型上来看,流主要分为字符流(InputStream, OutputStream)和字节流(Reader, Writer),而从功能上来看,主要分为输入流以及输出流.
文件的读写
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使用
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();
}
}
时间: 2024-10-10 04:27:08