【Java】java 的!file.exists()與 file !=null使用場景/區別

 1.exists()方法使用

//這裏使用new 創建實例,所以f不可能爲null
File f = new File("D:/xyz/hashdog.text")

//用exists()方法判斷
if(!f.exists()){
    System.out.print("該文件不存在")
}

2.!=null條件使用

//這裏使用new 創建實例,所以f不可能爲null
File f ;
//xxx代表業務中的條件表達式
if(xxx){
    f = new File("D:/xyz/hashdog.text")
}

//這裏要使用!=null判斷,可能存在空指針
if(f != null && !f.exists()){
    System.out.print("該文件不存在")
}

 

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