java如何判断是否为文件

内容摘要
表示此抽象路径名的文件是一个文件,该方法返回true,否则该方法返回false。异常 (推荐学习:java课程)SecurityException -- 如果安全管理器存在并且其SecurityMa
文章正文

表示此抽象路径名的文件是一个文件,该方法返回true,否则该方法返回false。

异常 (推荐学习:java课程)

SecurityException -- 如果安全管理器存在并且其SecurityManager.checkRead(java.lang.String) 方法拒绝对文件的读访问

例子

下面的示例演示java.io.File.isFile()方法的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.test;
 
import java.io.File;
 
public class FileDemo {
   public static void main(String[] args) {
       
      File f = null;
      String path;
      boolean bool = false;
       
      try{
         // create new file
         f = new File("c:");
             
         // true if the file path is a file, else false
         bool = f.isFile();
          
         // get the path
         path = f.getPath();
          
         // prints
         System.out.println(path+" is file? "+ bool);
                
         // create new file
         f = new File("c:/test.txt");
          
         // true if the file path is a file, else false
         bool = f.isFile();
          
         // get the path
         path = f.getPath();
          
         // prints
         System.out.print(path+" is file? "+bool);
          
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

让我们编译和运行上面的程序,这将产生以下结果:

1
2
c: is file? false
c:est.txt is file? true

 

代码注释
[!--zhushi--]

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!