File類createNewFile時的一個注意點

 

 

今天體會到一個陷阱,剛開始還覺得是JDKbug呢,呵呵。

 

是這樣的,有FilecreateNewFile方法是,在Windows系統上可以創建成功,而在Linux不行了,第一感覺是JDKbug,而且只會在Linux上出現的取決於。

 

原來一番實驗後,發現原來我Windows系統上已經有父目錄了,而Linux上沒有,這樣一來,Linux上肯定會失敗了。

 

寫下來記在這裏。

 

實驗代碼如下:

 

 

 

public static void main(String[] args) throws IOException {
		String filePath = "."+File.separator +"farParentfile" + File.separator + "parentFile"+File.separator + "test.jsp";
		
		File file = new File(filePath);
		
		
		if (!file.getParentFile().exists()) {
			if (!file.getParentFile().mkdirs()) {
			}
		}

		
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("exist: " +file.exists() );
		
		System.out.println("path: " + file.getCanonicalPath());
	}
 

 

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