- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在测试通过 FileChannel.open() 和 RandonAccessFile.getChanel() 获取的 NIO File Lock。
发现通过FileChannel.open()获取的FileLock可以移动文件,而通过RandonAccessFile.getChanel()获取的FileLock则不能移动。
FileChannel.open()
File file = new File("../tmp/test.txt");
FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE);
FileLock fileLock = fileChannel.lock();
System.out.println("file locked");
boolean result = file.renameTo(new File("../tmp/test2.txt"));
System.out.println("rename result " + result);
fileLock.release();
fileChannel.close();
RandonAccessFile.getChanel()
File file = new File("../tmp/test.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws");
FileChannel newChannel = (randomAccessFile).getChannel();
FileLock fileLock = newChannel.lock();
System.out.println("File locked");
boolean result = file.renameTo(new File("../tmp/test2.txt"));
System.out.println("rename result " + result);
最佳答案
Java 文件锁定的行为是高度特定于平台的,renameTo
的行为也是如此,包括它与显式锁定或以其他方式“使用”的文件的交互。
在 Windows 中,某些文件“打开”操作将锁定整个文件,并且重命名对锁定的文件不起作用。 (事实上,我怀疑即使您注释掉了 lock()
调用,使用 getChannel()
的代码版本也会失败。但我没有 Windows机器来测试这个。)
相比之下,Linux 在打开文件时不会锁定文件,并且您可以重命名打开的文件。
如何处理这个问题?
如果你希望你的代码是跨平台的,你需要非常保守。例如,不要尝试重命名应用程序当前打开的文件。重命名之前关闭所有文件“句柄”。
或者,编写代码以了解平台,并根据需要在不同平台上执行不同的操作。 (我无法准确地建议什么,因为您的示例没有告诉我们您实际上想要实现的目标。)
关于java - 为什么当通过 FileChanel.open() 而不是 RandomAccessFile.getChannel() 获取文件锁时可以移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576072/
在 twilio 聊天中,有没有一种方法可以指定 getChannels() 方法的顺序?或者 Channel 对象上是否有一个属性可以告诉我在该 channel 上发送的最后一条消息是什么时候? C
我正在处理 I/O 并在 Internet 上找到了 java.io.FileInputStream.getChannel()。我想知道 getChannel 的确切目的。为什么我们需要使用 java
本文整理了Java中com.zsmartsystems.zigbee.ZigBeeChannel.getChannel()方法的一些代码示例,展示了ZigBeeChannel.getChannel()
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
任何人都可以帮我解决这部分代码吗?在我说别的之前,“FillerId”实际上并不存在于实际代码中,它被替换为 discord 文本 channel 的正确 channel ID。我在这段代码中遇到的错
我正在测试通过 FileChannel.open() 和 RandonAccessFile.getChanel() 获取的 NIO File Lock。 发现通过FileChannel.open()获
我是 Clojure 的新手,我需要 Clojure 为我做一个简单的任务,相当于下面的 Java 代码: MappedByteBuffer out = new RandomAccessFile("f
我是一名优秀的程序员,十分优秀!