Java IO創(chuàng)建目錄和文件實例代碼
更新時間:2018年02月28日 10:02:46 作者:彬菌
本篇文章給大家分享了Java IO創(chuàng)建目錄和文件的實例代碼,過程很簡單,大家可以測試參考下。
我們先來看下具體代碼:
import java.io.File; import java.io.IOException; public class CreatFile{ public static void main(String[] args) { File newDir=new File("D:/test"); //聲明磁盤目錄 File newFile = new File(newDir,"test.txt"); //聲明目錄文件 boolean newCreatDir=newDir.exists(); boolean newCreatFile=newFile.exists(); //創(chuàng)建目錄及文件 if(newCreatDir==false){ try{ //異常監(jiān)聽 newDir.mkdirs(); //創(chuàng)建目錄 System.out.println(newDir.getAbsolutePath()+"目錄已創(chuàng)建"); newFile.createNewFile(); //創(chuàng)建文件 System.out.println(newFile.getAbsolutePath()+"文件已創(chuàng)建"); } catch(IOException e){ //捕捉異常 e.printStackTrace(); //在命令行打印異常信息在程序中出錯的位置及原因 } } else{ System.out.println(newDir.getAbsolutePath()+"目錄已存在"); } if(newCreatFile==true){ System.out.println(newFile.getAbsolutePath()+"文件已存在"); } } }
說明:
創(chuàng)建目錄的方法,mkdirs();或者mkdir(); 區(qū)別在于mkdirs()可以多級創(chuàng)建。
創(chuàng)建文件方法,createNewFile();
相關文章
SpringBoot+Vue前后端分離實現(xiàn)審核功能的示例
在實際開發(fā)中,審核功能是一個非常常用的功能,本文就來介紹一下使用SpringBoot+Vue前后端分離實現(xiàn)審核功能的示例,具有一定的參考價值,感興趣的可以了解一下2024-02-02