2016年9月21日 星期三

How to create file and directory in Java.

String filePath = "logs/test.log";
File file = new File(filePath);
此時如果直接createNewFile()
if(!file.exists())
{
 try {
  file.createNewFile();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
會因為parent的資料夾不存在而失敗,而這時直接使用mkdirs()

if(!file.exists())
{
 file.mkdirs();
 try {
  file.createNewFile();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
但這樣會把01.log也當成資料夾建立,就無法createNewFile,所以應該先切換到上層目錄再進行mkdirs()
if(!file.exists())
{
 file.getParentFile().mkdirs();
 try {
  file.createNewFile();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}

沒有留言:

張貼留言