62,628
社区成员
发帖
与我相关
我的任务
分享package interview_prepared;
import java.io.File;
//实现文件读写加锁
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileReadWrite
{
public static void main(String[] args) throws IOException, InterruptedException
{
//String path = Thread.currentThread().getContextClassLoader().getResource("F:\\java\\java_code\\review\\ReadFile.java").getPath();
File file = new File("F:\\java\\java_code\\review\\ReadFile.java");
try
{
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream("writehere.txt");
FileChannel fcin = fis.getChannel();
FileChannel fcout = fos.getChannel();
FileLock flin = null;
while(true){
try {
flin = fcin.tryLock();
break;
} catch (Exception e) {
System.out.println("有其他线程正在操作该文件,当前线程休眠1000毫秒");
Thread.sleep(1000);
}
}
ByteBuffer bbuffin = ByteBuffer.allocate(32);
while(fcin.read(bbuffin)!= -1)
{
bbuffin.flip();
FileLock flout = fcout.tryLock();
fcout.write(bbuffin);
flout.release();
System.out.println(bbuffin);
bbuffin.clear();
}
flin.release();
fos.close();
fis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}