我制作了两个设计为同时运行的应用程序(我不想合并它们),一个从某个文件读取,另一个向该文件写入。当其中一个运行时没有错误,但是如果它们都运行 get,则会出现访问被拒绝错误。 第一条相关代码:
class MakeImage implements Runnable {
@Override
public void run() {
File file = new File("C:/Users/jeremy/Desktop/New folder (3)/test.png");
while (true) {
try{
//make image
if(image!=null)
{
file.createNewFile();
ImageIO.write(image, "png", file);
hello.repaint();}}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
第二个相关代码:
BufferedImage image = null;
try {
// Read from a file
image = ImageIO.read(new File("C:/Users/jeremy/Desktop/New folder (3)/test.png"));
}
catch(Exception e){
e.printStackTrace();
}
if(image!=null)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "png", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
returns=Base64.encodeBase64String(imageInByte);
}
我看了这个:Java: how to handle two process trying to modify the same file ,但那是当两者都写入文件时,这里只有一个。我按照前者的答案中的建议尝试了稍后重试的方法,但没有任何运气。任何帮助将不胜感激。
最佳答案
除非您使用某种操作系统级别的文件锁定并检查锁定,否则您将无法轻松可靠地完成此操作。管理此问题的一种相当可靠的方法是使用目录中的另一个文件作为信号量,在写入或读取时“触摸”它,并在完成后将其删除。在访问文件之前检查信号量是否存在。否则,您将需要使用某种数据库来存储文件锁(保证一致性)并在那里检查它。
也就是说,您确实应该将其合并到 1 个程序中。
关于JAVA:我的两个应用程序如何访问同一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11528295/