Java I/O
Input : 输入 -> 从外部往内存 Output : 输出 -> 从内存往外部 Java 中是通过流Stream的方式,实现文件的读写,本质上就是通过stream流进行读和写
buffer read
buffer write
private static void io6() {
try (Socket socket = new Socket("hencoder.com", 80);
//发送请求报文
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//接收响应报文的
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
// Socket socket = new Socket("hencoder.com", 80);
//发送请求报文
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//接收响应报文的
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.write("GET / HTTP/1.1\n" +
"Host: www.example.com\n\n");
writer.flush();
String message;
while ((message = reader.readLine()) != null) {
System.out.println(message);//HTTP/1.1 200 OK
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void io7() {
try (ServerSocket serverSocket = new ServerSocket(80);
//阻塞 等客户端连接服务端
Socket socket = serverSocket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
//创建一个服务端Socket
// ServerSocket serverSocket = new ServerSocket(80);
//阻塞 等客户端连接服务端
// Socket socket = serverSocket.accept();
writer.write("hello test");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读写字符串
*/
private static void io3() {
//try() 自动关闭流
try (InputStream inputStream = new FileInputStream("./io.text.txt");
Reader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader)
) {
//Reader reader = new FileReader();//直接戳文件
// Reader reader = new InputStreamReader(inputStream);//reader -> stream -> file
//Reader Writer 写字符串的流
//BufferedReader 可以读取一行数据
// BufferedReader bufferedReader = new BufferedReader(reader);//bufferreader -> reader -> stream -> file
System.out.println(bufferedReader.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读文件 input,从外部输入到内存
* 读文件和写文件,都需要插一个管子,
*/
private static void io2() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("./io.text.txt");
System.out.println((char) inputStream.read());
System.out.println((char) inputStream.read());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 写文件 output,从内存输出到外部
*/
private static void io1() {
//Java 7 的写法,写到try() 当try执行完毕,会自动关闭流
try (OutputStream outputStream = new FileOutputStream("./io.text.txt")) {
//相当于从 程序的内存 和 外部,搭建了一个桥梁
outputStream.write('a');
outputStream.write('b');
//Reader Writer 写字符串的流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* BufferedOutputStream
*/
private static void io4() {
//Java 7 的写法,写到try() 当try执行完毕,会自动关闭流
try (OutputStream outputStream = new FileOutputStream("./io.text.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
// BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
//相当于从 程序的内存 和 外部,搭建了一个桥梁
//c d -> buffer 只是先放到缓冲区了 没有写入到文件中 减少和文件的直接操作 提升性能
bufferedOutputStream.write('q');
bufferedOutputStream.write('a');
//flush 将缓冲区的数据一块 这样效率更高 buffer -> stream -> file
// bufferedOutputStream.flush();
//flush实际意义:手动调用flush 可以先同步一部分数据,后面继续在缓冲区接收数据 当达到某个阈值 调用flush同步数据
//close 关闭的时候 也会将缓冲区的数据 冲到文件中
// bufferedOutputStream.close();
//Reader Writer 写字符串的流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 循环的读和写
*
* @throws IOException
*/
private static void io5() {
try (InputStream inputStream = new BufferedInputStream(new FileInputStream("./io.text.txt"));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("./io.new_text.txt"))) {
byte[] data = new byte[1024];
int read;//把外部的文件 读取到data中,read 读取的个数
while ((read = inputStream.read(data)) != -1) {
outputStream.write(data, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
NIO
传统IO:Stream;NIO:Channel 双向,NIO Buffer 可以被操作的;强制使用Buffer(buffer不还用) 支持非阻塞式,默认是阻塞式的,只有网络交互支持非阻塞,文件交互不支持。
//NIO 非阻塞式 必须是网络交互
private static void io9() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(80));
serverSocketChannel.configureBlocking(false);//非阻塞
Selector selector = Selector.open();
//accept 行为变成了非阻塞式的
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//阻塞的
while (true) {
selector.select();//这里变成了阻塞
for (SelectionKey selectedKey : selector.selectedKeys()) {
if (selectedKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (socketChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
//还4回去
socketChannel.write(byteBuffer);
byteBuffer.clear();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void io8() {
try {
RandomAccessFile file = new RandomAccessFile("./io.text.txt", "r");
FileChannel channel = file.getChannel();
//将问价内容读取到 buffer中去
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
channel.read(byteBuffer);
byteBuffer.limit(byteBuffer.position());//把position 交给limit
byteBuffer.position(0);
// byteBuffer.flip(); 等价于上面的两行
System.out.println(Charset.defaultCharset().decode(byteBuffer));
//每次读写完后将position 和 limit重置
byteBuffer.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
okio
/**
* 基于插管的 单向:Source 输入、Sink输出
* 支持Buffer 可以对Buffer进行操作 很好用的 不强制使用Buffer
* 和传统IO很像
*/
private static void okio() {
try(BufferedSource source = Okio.buffer(Okio.source(new File("./io.text.txt")))) {
//BufferedSource Okio.buffer
System.out.println(source.readUtf8Line());
// Okio.sink().write();
//Okio.source
Buffer buffer = new Buffer();
//读source 写到buffer中去
source.read(buffer,1024);
//读buffer
System.out.println(buffer.readUtf8Line());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}