我有一个显示的代码,它可以成功运行。但是,在包含注释行lock =f.tryLock()
时,它会抛出IOException。这是因为锁定了文件。我不希望读取/复制锁文件(我需要从InputStream过滤锁文件),因此在这种情况下代码不应该抛出IOException。有人可以帮我吗?
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
public class Lock {
public static void main(String args[]) throws IOException, InterruptedException {
RandomAccessFile file = null; // The file we'll lock
FileChannel f = null; // The channel to the file
FileLock lock = null; // The lock object we hold
OutputStream out = null;
InputStream in = null;
try {
String tmpdir = System.getProperty("java.io.tmpdir");
String filename = Lock.class.getName() + ".lock";
File lockfile = new File(tmpdir, filename);
file = new RandomAccessFile(lockfile, "rw");
f = file.getChannel();
// lock = f.tryLock();
in = new FileInputStream(lockfile);
byte[] buffer = new byte[1024];
if(in.read(buffer)!=0){
int len = in.read(buffer);
while (len != -1) {
out.write(buffer, 0, len);
len = in.read(buffer); }
}
in.close();
if (lock != null) {
lockfile.deleteOnExit(); // Just a temporary file
}
} catch (IOException e) {
System.out.println(e);
throw e;
}
finally{
if (lock != null && lock.isValid())
lock.release();
if (file != null)
file.close();
}
}
}
例外:
java.io.FileNotFoundException: The system cannot find the file specified
Exception in thread "Main Thread" java.io.FileNotFoundException: The system cannot find the file specified
at java.io.FileInputStream.readBytes(FileInputStream.java)
at java.io.FileInputStream.read(FileInputStream.java:198)
at Lock.main(Lock.java:32)
答案 0 :(得分:0)
如果您在读取锁定文件时可靠地获得某种类型的IOException,那么仅仅捕获它并中止/清理副本似乎可以完全解决您的问题。无论如何,你必须在任何IOException上这样做,而不仅仅是这个,所以这种情况并没有什么特别之处。
InputStream.available()与文件锁或文件大小无关。见Javadoc。