java 中IO流是基础,包括文件IO,网络IO,控制台,数据库连接等。
从流的格式分类上有:
字节流
过滤的字节流:可以进行压缩等改变字节的操作
字符流(Reader,Writer)
类图:
由类图结构可以看到,SockertInputStream 继承了FileInputStream ,也属于一切皆文件的描述,可以使用fd创建流。
FileChannel (通道)从流获取,Channel,Buffer 是NIO(new ) api
来个代码例子,使用FileChannel ,公用同一个buffer,将一个文件中的内容不断向另一个文件拷贝。
package test.java.io;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
public class StreamTest {
public static void main(String[] args) throws IOException, InterruptedException {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byte[] bytes = new byte[1028];
String l = "l";
Lock lock = new ReentrantLock();
Condition pCondition = lock.newCondition();
Condition cCondition = lock.newCondition();
Thread t1 = new Thread(() -> {
FileInputStream in = null;
try {
in = new FileInputStream("/Users/a.text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel fileChannel = in.getChannel();
while (true) {
try {
lock.lock();
byteBuffer.clear();
int i = fileChannel.read(byteBuffer);
byteBuffer.flip();
Thread.sleep(100);
System.out.println("in--->" + i + " " + new String(byteBuffer.array()));
cCondition.signal();
pCondition.await();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}, "in");
Thread oT = new Thread(() -> {
FileOutputStream out = null;
try {
out = new FileOutputStream("/Users/a_copy.text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel outChannel = out.getChannel();
while (true) {
try {
lock.lock();
Thread.sleep(100);
System.out.println("out--->" + byteBuffer.arrayOffset() + new String(byteBuffer.array()));
outChannel.write(byteBuffer);
byteBuffer.clear();
pCondition.signal();
cCondition.await();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}, "out");
t1.start();
oT.start();
Thread.sleep(30000l);
}
private static void sysIn() throws IOException {
InputStream in = System.in;
byte[] bytes = new byte[1024];
int i = 0;
FileOutputStream outputStream = new FileOutputStream("/Users/a.text");
while ((i = in.read()) != -1) {
char a = (char) i;
System.out.print(a);
outputStream.write(a);
}
// while ((i = in.read(bytes)) != 0) {
System.out.println(new String(bytes));
// byte[] temp1 = new byte[i];
// System.arraycopy(bytes, 0, temp1, 0, i);
// System.out.println(new String(temp1));
// }
}
}