JAVA的File對象

文件1.File對象java封裝的一個操作文件及文件夾(目錄)的對象 ??梢圆僮鞔疟P上的任何一個文件和文件夾 。
2.創建文件 方式一:根據路徑構建一個File對象new File(path)
//方式一@Testpublic void create01(){try {String path = URLDecoder.decode("D:\\博客園\\wjj1.txt","UTF-8");//解決中文亂碼,轉UTF-8File 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)
//方式二@Testpublic 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)
//方式三@Testpublic 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");}運行結果:

JAVA的File對象

文章插圖
3.文件的相關操作文件的路徑相關和判斷功能的構造方法
@Testpublic 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一個英文一個字節,一個漢字三個字節
運行結果:
JAVA的File對象

文章插圖
文件刪除操作的構造方法
@Testpublic 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("文件不存在");}}文件創建目錄操作的構造方法
@Testpublic 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("創建失敗");}}}運行結果:
JAVA的File對象

文章插圖
【JAVA的File對象】

    推薦閱讀