初学者关于读写文件加锁 基础问题一点 报占用一点小疑惑 百思不得其解 求解答

TS败类 TS败类 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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();
}


}

}

上面是我本人的程序 那天偶然看见有人说读写文件加锁的问题 我就自己写了一个 发现有错误 一直提示 读文件加锁加不上,一直卡其他进程占用 注释掉读文件部分之后 发现写文件可以加锁加上,不知道是什么问题,想请教一下大家。下面给出控制台 拜托啦 谢谢 谢谢
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
TS败类
Java SE 62,620 成员 307,251 内容