我有两种方法-一种编写,第二种重命名文件:
public void writeToFile(File file, String content, boolean isLastLine) {
Optional<File> optionalFile = Optional.ofNullable(file);
if (!isLastLine)
content += System.lineSeparator();
try {
Files.write(
optionalFile.orElseThrow(() -> new RuntimeException("File couldn't be find")).toPath(),
content.getBytes(),
StandardOpenOption.APPEND, StandardOpenOption.SYNC);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void renameFile(File fileToRename, String newFileName) {
Optional<File> optionalFile = Optional.ofNullable(fileToRename);
File finalBikFileName = new File(newFileName);
if (!optionalFile.orElseThrow(() -> new RuntimeException("File couldn't be find or doesn't exist")).renameTo(finalBikFileName)) {
throw new RuntimeException("File couldn't be saved - already exists or some other issues");
}
}
public void renameFile(File fileToRename, String newFileName) {
Optional<File> optionalFile = Optional.ofNullable(fileToRename);
File finalBikFileName = new File(newFileName);
if (!optionalFile.orElseThrow(() -> new RuntimeException("File couldn't be find or doesn't exist")).renameTo(finalBikFileName)) {
throw new RuntimeException("File couldn't be saved - already exists or some other issues");
}
}
这是普通的类,在Wildfly上部署的应用程序中。我以多种方式对其进行了测试。如果我评论写功能,那么重命名功能可以正常工作。但是,如果我先向文件写入内容,然后想重命名,那么我会收到“无法完成操作,因为文件已在另一个程序中打开”,而且我无法在Windows资源管理器中触摸此文件-我无法重命名或删除。可能是什么原因?如何解锁?
1)调用writeToFile和renameFile方法的是不同的线程(或服务器请求)吗?还是这两种方法在同一线程/请求下一个接一个地调用?2)您正在写入多少数据(我指的是content.length)?只想确保在RENAME之前完成SYNC。