JAVA的File對象

文件

1.File對象 

        java封裝的一個操作文件及文件夾(目錄)的對象。可以操作磁碟上的任何一個文件和文件夾。

2.創建文件

   方式一:根據路徑構建一個File對象new File(path)

//方式一
    @Test
    public void create01(){
        try {
            String path = URLDecoder.decode("D:\\部落格園\\wjj1.txt","UTF-8");//解決中文亂碼,轉UTF-8
            File file = new File(path);
            file.createNewFile();
            System.out.println("創建成功01");
        } catch (UnsupportedEncodingException e) {//decode方法需要拋異常或捕獲異常
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    方式二:根據父目錄文件和子目錄路徑構建一個File對象new File(File,Spath)   

//方式二
@Test
public void create02(){ String path = null; try { path = URLDecoder.decode("D:\\部落格園","UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File parentFile = new File(path);//父目錄文件 String fileName = "wjj2.txt";//子路徑 File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("創建成功02"); } catch (IOException e) { e.printStackTrace(); } }

     方式三:根據父目錄路徑和子目錄路徑構建一個File對象new File(Fpath,Spath)

//方式三
    @Test
    public void create03() throws Exception{//拋異常
        String path = URLDecoder.decode("D:\\部落格園","UTF-8");
        String filePath = "wjj3.txt";
        File file = new File(path, filePath);
        file.createNewFile();
        System.out.println("創建成功03");
    }

     運行結果:

  3.文件的相關操作

   文件的路徑相關和判斷功能的構造方法

 

    @Test
    public void info() throws Exception{
        //創建文件對象
        String path = URLDecoder.decode("D:\\部落格園\\wjj1.txt","UTF-8");
        File file = new File(path);
        System.out.println("文件名:"+file.getName());
        System.out.println("文件絕對路徑:"+file.getAbsolutePath());
        System.out.println("文件父目錄:"+file.getParent());
        System.out.println("文件大小(位元組):"+file.length());
        System.out.println("文件是否存在:"+file.exists());
        System.out.println("是否是文件:"+file.isFile());
        System.out.println("是否是目錄:"+file.isDirectory());
    }

 

    UTF-8一個英文一個位元組,一個漢字三個位元組

    運行結果:

    文件刪除操作的構造方法

    @Test
    public void fileDelete() throws Exception{
        String path = URLDecoder.decode("D:\\部落格園\\wjj1.txt","UTF-8");
        File file = new File(path);
        if (file.exists()){
            if (file.delete()){
                System.out.println(path+"刪除成功");
            }else {
                System.out.println(path+"刪除失敗");
            }
        }else {
            System.out.println("文件不存在");
        }
    }

    文件創建目錄操作的構造方法

    @Test
    public void isMkdir() throws Exception{
        String path = URLDecoder.decode("D:\\部落格園\\wjj1","UTF-8");
        File file = new File(path);
        if (file.exists()){
            System.out.println(path+"該目錄已存在");
        }else {
            if (file.mkdirs()){
                System.out.println("創建成功");
            }else {
                System.out.println("創建失敗");
            }
        }
    }

    運行結果:

 

Tags: