java file.renameTo()在unix中失败
我有一个处理文件内容的java应用程序,然后我需要将其移动到另一个位置 以下是我读取文件的方式:java file.renameTo()在unix中失败,java,unix,java-6,file-rename,Java,Unix,Java 6,File Rename,我有一个处理文件内容的java应用程序,然后我需要将其移动到另一个位置 以下是我读取文件的方式: String filePath = new String("foo.bar"); String fileContents = new String(""); char[] myBuffer = new char[chunkSize]; int bytesRead = 0; BufferedReader in; try { FileRea
String filePath = new String("foo.bar");
String fileContents = new String("");
char[] myBuffer = new char[chunkSize];
int bytesRead = 0;
BufferedReader in;
try {
FileReader fr = new FileReader(filePath);
in = new BufferedReader(fr);
try {
while ((bytesRead = in.read(myBuffer,0,chunkSize)) != -1)
{
//System.out.println("Read " + bytesRead + " bytes. They were: " + new String(myBuffer));
fileContents+= new String(myBuffer).substring(0, bytesRead);
}
// close the stream as I don't need it anymore. (If I don't close it, then java would hold the file open thus preventing the subsequent move of the file)
in.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
当我关闭输入流和文件读取器时,应该关闭文件
然后,我尝试使用file.renameTo(newFileName)将文件移动到另一个目录代码>但这失败了(在unix!下,在windows下工作正常)
移动失败后,我立即测试是否可以创建名为newFileName
的文件,以及是否可以删除原始文件。新文件将被创建,而原始文件无法删除。
有趣的是,我可以在应用程序运行时(故障发生后)从命令行删除原始文件
你知道这是为什么还是其他选择吗
更多详细信息:我在unix下工作,出于遗留原因,我必须使用java 1.6(因此我无法恢复到从java 1.7开始支持的Files.move()。我发现了java应用程序中的问题所在
基本上,我使用自定义的FileFilter
从目录中提取文件列表。这给了我一个数组文件[]foundFiles
。
之后我要做的是使用问题中的代码片段在while循环中读取每个文件。
由于某种原因读取文件之后,我使用数组中的第I个文件作为构造函数的参数,创建了一个新的文件
对象
File file = new File(foundFiles[i].getName()); // File to be moved
然后我试着重新命名这个
现在,由于某种原因,它在windows下工作,而在unix下不工作(我认为文件被foundFiles[I]
对象以某种方式锁定)
事实上如果我打印这些行的结果
System.out.println("I can read foundFiles[i]: " +foundFiles[i].canRead());// DEBUG
System.out.println("I can write foundFiles[i]: " +foundFiles[i].canWrite());// DEBUG
System.out.println("I can read file : " +file.canRead());// DEBUG
System.out.println("I can write file : " +file.canWrite());// DEBUG
我明白了
I can read foundFiles[i]: True
I can write foundFiles[i]: True
I can read file: False
I can write file: False
只需在foundFiles[i]
对象上直接使用renameTo()
,即可使其正常工作
希望这能有所帮助,但我不知道为什么第一个版本可以在windows下工作而不能在unix下工作。让我们分析一下上面的观察结果
I can read foundFiles[i]: True
I can write foundFiles[i]: True
I can read file: False
I can write file: False
结果是正常的,因为文件对象是通过新文件(foundFiles[i].getName())生成的,但是方法getName只提供文件名,不提供文件路径
通过新建文件(foundFiles[i].getParent()+file.separator+foundFiles[i].getName())创建文件,结果将是:
I can read foundFiles[i]: True
I can write foundFiles[i]: True
I can read file: True
I can write file: True
是否将其移动到其他文件系统/NFS?是否检查了由代码创建的文件的属性可能是JVM没有访问该文件的权限,或者您的应用程序代码作为别名运行,但没有读/写访问权限?@dogbane否我实际上将其移动到创建原始文件的文件夹的子文件夹中(子文件夹存在)。@VivekBajpai java应用程序确实具有读/写权限(事实上,它读取原始文件-我可以看到一些日志文件中的内容),并且它可以创建文件(我可以在我希望将原始文件移到的位置创建一个空白文件)我知道,但是为什么不用ls-l检查文件属性呢?我会在创建文件和文件无法移动时都尝试一下