溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java IO創(chuàng)建目錄和文件實例代碼

發(fā)布時間:2020-10-21 12:22:17 來源:腳本之家 閱讀:166 作者:彬菌 欄目:編程語言

我們先來看下具體代碼:

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();

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI