下面的案例证明了文件读取操作和文件写出操作可以同时进行,文件写出和文件写出也可以同时进行
package com.sun.redis;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class T {
public static void main(String[] args) {
//文件写出操作
new Thread(() -> fileOut((byte) 97)).start();
//文件写出操作
new Thread(() -> fileOut((byte) 107)).start();
//读取文件操作
new Thread(() -> fileIn()).start();
}
private static void fileIn() {
File file = new File("C:\\Users\\jiuhui-4\\Desktop\\test.txt");
try {
Thread.sleep(1000);
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[1];
int n = 0;
while ((n = fis.read(bytes)) > 0) {
for (byte aByte : bytes) {
System.out.println(aByte);
Thread.sleep(1000);
}
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void fileOut(byte num) {
File file = new File("C:\\Users\\jiuhui-4\\Desktop\\test.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
for (int i = num; i < num + 10; i++) {
byte[] bytes = {(byte) i};
fos.write(bytes);
Thread.sleep(1000);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}