写文件路径的三种方式:
1 package object.io; 2 3 import java.io.File; 4 5 public class Main { 6 public static void main(String[] args) { 7 // File file=new File("D:\Program Files (x86)\io\first.txt");//方法一 8 9 // File file=new File("D:\Program Files (x86)\io","first.txt");//方法二 10 11 File file1=new File("D:\Program Files (x86)\io"); 12 File file=new File(file1,"first.txt"); //方法三 13 14 if(file.exists()){ 15 System.out.println("文件存在"); 16 }else{ 17 System.out.println("文件不存在"); 18 } 19 20 } 21 }
File类的常用方法:
1 package object.io; 2 3 import java.io.File; 4 5 public class Main { 6 public static void main(String[] args) { 7 8 File file1=new File("D:\Program Files (x86)\io"); 9 File file=new File(file1,"first"); 10 11 System.out.println(file.getAbsolutePath()); //(获得全路径) 结果:D:Program Files (x86)iofirst 12 System.out.println(file.getName()); //first 13 System.out.println(file.getParent()); //D:Program Files (x86)io 14 System.out.println(file1.isAbsolute()); //true 15 16 } 17 }
创建文件:createNewFile()
1 package object.io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class Main { 7 public static void main(String[] args) throws IOException { 8 9 File file1=new File("D:\Program Files (x86)\io\create1.jpg");//在已存在的路径下创建文件 10 boolean flag=file1.createNewFile(); 11 if(flag){ 12 System.out.println("文件创建成功"); 13 }else{ 14 System.out.println("文件创建失败"); 15 } 16 17 18 } 19 }
创建单层文件夹:mkdir():
1 package object.io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class Main { 7 public static void main(String[] args) throws IOException { 8 9 File file1=new File("D:\Program Files (x86)\io\file1"); 10 file1.mkdir(); 11 12 13 } 14 }
创建多重文件夹:mkdirs();
1 package object.io; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 public class Main { 7 public static void main(String[] args) throws IOException { 8 9 File file1=new File("D:\Program Files (x86)\io\file2\file21"); 10 file1.mkdirs(); 11 12 13 } 14 }
listFiles()获取该目录下有几个文件,得到的是一个File[]数组:
文件目录:
package object.io; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { File file=new File("D:\Program Files (x86)\io"); File[] files=file.listFiles(); System.out.println(files.length); for(int i=0;i<files.length;i++){ System.out.println(files[i]); } } }
打印结果: