天天看点

File类概述

public class FileDemo {

   public static void main(String[] args) {

 consMethod();

 }

    public static void consMethod(){

  //可以将已有的和未出现的文件封装成对象

  File file1=new File("G:\\d.txt");

  

  //将目录和文件名分开

  File d=new File("G:\\demo");

  File file2=new File(d,"d.txt");

  

  //File.separator跨平台的目录分隔符

  File file3=new File("G:"+File.separator+"d.txt");

  System.out.println(file1);

  System.out.println(file2);


   }
//****************
结果:
G:\d.txt
 G:\demo\d.txt
 G:\d.txt 

 public static void consMethod_2(){
 
  File file1=new File("G:\\dsds.txt");
  if(!file1.exists()){
  try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
  }
  
  System.out.println(file1.getPath());
  System.out.println(file1.getAbsolutePath());
  System.out.println(file1.getParent());//方法返回的是绝对路径的父目录G:\
  //如果写成File file1=new File("dsds.txt");则父目录返回为null


    }
}      

继续阅读