java在指定目錄下創建單個文件

代碼:

import java.io.File;
import java.io.IOException;
public class Test {
     
	
	/**
	 * 此方法的作用主要是判斷創建文件是否成功,成功則返回true,否則則返回false
	 * @param destFileName is 目標文件
	 * @return true or false
	 */
	public static boolean createFile(String destFileName){
		
		File file = new File(destFileName);//根據指定的文件名創建File對象
		
		//要創建的單個文件已存在
		if ( file.exists()){  
			System.out.println("文件"+destFileName+"已存在,創建失敗!" );
			return false;
		}
		
		
		//如果輸入的文件是以分隔符結尾的,則說明File對象是目錄而不是文件
		if ( destFileName.endsWith(File.separator)){  
			System.out.println("文件"+destFileName+"是目錄,目標文件不能是目錄,創建失敗!" );
			return false;
		}
		
		//判斷目標文件所在目錄是否存在
		if (!file.getParentFile().exists()){//如果目標文件所在文件夾不存在,則創建父文件夾
			System.out.println("創建"+file.getName()+"所在目錄不存在,正在創建!" );
			
			//判斷父文件夾是否存在,如果存在則表示創建成功,否則失敗
			if ( !file.getParentFile().mkdirs() ){
				System.out.println("創建目標文件所在目錄失敗!" );
				return false;
			}
		}
			
		
		//創建目標文件
		try{
			if ( file.createNewFile() ){
				System.out.println("創建單個文件"+destFileName+"成功!" );
				return true;
			}else{
				System.out.println("創建單個文件"+destFileName+"失敗!" );
				return false;
			}
		}catch(IOException e){//IOException異常需引入java.io.IOException包
			e.printStackTrace(); //在命令行打印異常信息在程序中出錯的位置及原因。
			System.out.println("創建單個文件"+destFileName+"失敗!" +e.getMessage());//e.getMessage()只會獲得具體的異常名稱
			return false;
		}
			
		
	}
	 
	
	
	/**創建單個文件 **/
    public static void main(String[] args){
    	 
    	//創建目錄
    	String dirName = "D:\\temp\\aa";
    	
    	//創建文件
    	String fileName = dirName+"\\bb\\ccfile.txt";
    	
    	Test.createFile(fileName);//調用創建目標文件方法
    	
    	 
    
 
     }
       
}

運行結果:

情況1 成功:
創建單個文件D:\temp\aa\bb\ccfile.txt成功!

在這裏插入圖片描述

情況2 文件已存在:
文件D:\temp\aa\bb\ccfile.txt已存在,創建失敗!






情況3 目標文件是一個目錄:
文件D:\temp\aa\bb\ccfile\是目錄,目標文件不能是目錄,創建失敗!

在這裏插入圖片描述

說明:

1、對於文件分割符,在windows中是“\”,而在Linux中是“/”,但是自己嘗試了一下,在windows中“/”也能用,例如:
在windows下:
File file = new File(“D:\\temp\\aa\\test.txt”)

則在Linux下要這麼寫:
File file = new File(“D:/temp/aa/test.txt”)

爲了考慮跨平臺,Java中提供了File.separator這一方式來表示文件分隔符:
File file = new File("D:”+File.separator+“temp”+File.separator+“aa”+File.separator+“test.txt”)

2、e.printStackTrace()和e.getMessage()的區別
e.printStackTrace(): 在命令行打印異常信息在程序中出錯的位置及原因。
e.getMessage(): 只會獲得具體的異常名稱

3、IOException異常需引入java.io.IOException包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章