文件在目录中,但isDirectory()为文件返回false
File is in the directory but isDirectory() returning false for a file
以下是代码片段:
String fileName = "High_Scores";
File file = new File(fileName + ".txt");
if(file.isFile())
System.out.println("its a file");
if(!file.isDirectory())
System.out.println("Not in directory");
if(file.delete())
System.out.println("deleted");
else
System.out.println(file.getAbsolutePath());
File file2 = new File(fileName + "2.txt");
boolean success = file2.renameTo(file);
if(success == true)
System.out.println("renamed");
else
System.out.println(file2.getAbsolutePath());
结果是isFile()返回true,isDirectory()返回false;delete和renameTo方法将不起作用。我不知道为什么isDirectory()返回false,因为file和file2都是在java项目文件夹中创建的。谢谢
您可能对file.isDirectory()
方法有一点误解。如果文件本身是一个目录,而不是文件在一个目录中,则返回true
。
我想您可能误解了File.isDirectory()
的作用。来自java 7 API:
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
Where it is required to distinguish an I/O exception from the case that the file is not a directory, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file
来自:Java 7文件API
因此,实际上,它正在测试该文件是否是一个目录,而不是它是否在其中:)
+1投赞成票,他打败了我!:D
您不是在用创建文件
new File
您缺少以下代码:
File file2 = new File(fileName + "2.txt");
file2.createNewFile();
相关文章:
- 如何播放部分音频文件
- 从桌面读取python文件时高亮显示代码
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何使用WCF服务和javascript表单post上传.doc文件
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 如何在生成下载文件时显示加载动画
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 如果 a 为 false,则 if(a) === if(false)
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何在php文件中获取$.post-ajax传递的值
- 直接下载文件,而不是从window.open(url)
- 如何在android中使用phonegap将文件从一个文件夹移动/复制到另一个文件夹
- PHP isset 在发送带有文件的 xhr 时返回 false
- 文件在目录中,但isDirectory()为文件返回false
- 如何将javascript变量传递给php文件,运行数据库查询并返回true或false
- 从noflo-nodejs开始——图<json文件>--batch—register false
- 为什么由gulp发出的乙烯基文件vinyl. isvinyl()返回false ?