1-创建File对象
1 /** 2 * 创建我们 java.io.File对象 3 */ 4 public static void test1() 5 { 6 //第一创建对象方式 7 File parent=new File("f:/lsh"); //设置一个目录对象 8 String child="刘诗华.txt"; //指定文件名 9 File file1=new File(parent, child); //目录对象,文件名 10 11 //第二种创建对象方式 指定一个文件名 表示方法为字符串 12 File file2=new File("f:/lsh/刘诗华.txt"); 13 14 //第三种创建方式 目录和文件都是用字符表示,但是目录和文件是分开来的 15 File file3=new File("f:/lsh/","刘诗华.txt"); 16 17 System.out.println("对象1="+file1); 18 System.out.println("对象2="+file2); 19 System.out.println("对象3="+file3); 20 21 //打印结果如下显示 22 //对象1=f:\lsh\刘诗华.txt 23 //对象2=f:\lsh\刘诗华.txt 24 //对象3=f:\lsh\刘诗华.txt 25 26 }
2.检查我们文件是否存在
public static void exists() { File file2=new File("f:/lsh/刘诗华.txt"); boolean b = file2.exists(); //如果硬盘上面存在刘诗华.txt文件 则会返回true 否则就是返回false System.out.println(b); //因为我的电脑上面没有文件,所以返回false }
原文:https://www.cnblogs.com/hua900822/p/9671420.html