【发布时间】:2011-06-14 14:27:35
【问题描述】:
所以我尝试锁定文件来读取它,但我得到了 IOException,知道为什么吗?
public static void main(String[] args){
File file = new File("C:\\dev\\harry\\data.txt");
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileChannel channel = null;
FileLock lock = null;
try{
channel = new RandomAccessFile(file, "rw").getChannel();
lock = channel.lock();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
String data;
while((data = bufferedReader.readLine()) != null){
System.out.println(data);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
lock.release();
channel.close();
if(bufferedReader != null) bufferedReader.close();
if(fileReader != null) fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我收到了这个错误IOException: The process cannot access the file because another process has locked a portion of the file
【问题讨论】:
-
锁定文件后是不是就不用NIO的方法来访问了?
-
@Jeff:我不确定。这是我第一次写代码锁定文件。
-
是在其他任何地方打开的文件(可能在某个编辑器中锁定了它打开的所有内容(就像 M$ 工具一样))
-
@Jeff,该死的。你怎么能捡起我没想到的东西。我要睡觉了。
-
@Harry,我相信他是对的。 FileChannel 类具有读取和写入方法。使用这些可以防止出现问题。使用 FileReader 最终会使用不同的文件描述符。