文件1.File對象java封裝的一個操作文件及文件夾(目錄)的對象 。可以操作磁盤上的任何一個文件和文件夾 。
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");}運行結果:

文章插圖
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());}【JAVA的File對象】UTF-8一個英文一個字節,一個漢字三個字節
運行結果:

文章插圖
文件刪除操作的構造方法
@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("創建失敗");}}}運行結果:

文章插圖
經驗總結擴展閱讀
- 多情總被無情傷 這些星座是愛情里的傻瓜
- 秋天冰箱的溫度怎么調才正確 冰箱不制冷的原因是什么
- 性格堅強的三大星座女 卻最讓人心疼
- 外出發展 最易發財的星座
- 畫餅專家 這些星座男的話不能全信
- 2023年9月13日是剪指甲吉日嗎 2023年9月13日是剪指甲的黃道吉日嗎
- 工資過10萬的十大職業 哪些工作工資超高
- 2023年9月13日是年前洗澡的黃道吉日嗎 2023年農歷七月廿九年前洗澡吉日
- 十二星座秉承單身主義的原因 遇不到對的人還是享受孤獨
- 京東付尾款的時候可以改地址嗎 京東收貨地址填錯了怎么辦
