【Java】利用內建的file.mkdirs();建立檔案夾與file.mkdirs();的注意事項

來源:互聯網
上載者:User

標籤:java   檔案夾   mkdir   控制台   異常   

利用Java的內建命令file.mkdirs();是可以直接在系統建立檔案夾的。

比如在d:\1檔案夾下建立一個2的檔案夾,則這樣寫:

import java.io.*;public class FileMkdirTest {public static void main(String[] args) {File file = new File("d:\\1\\2");//如果d:\1\2這個檔案夾不存在,才建立if (!file.exists()) {file.mkdirs();}}}

Java把檔案夾也視作一個file,

但值得注意的是,在檔案夾或檔案名稱中不得含有:兩個方向的斜杠\/、冒號:、星號*、問號?、引號"、左右角括弧<>、豎杠|,你要使用這個符號作為檔案夾或檔案名稱,最好把他們轉化成全形\/:*?"<>|,可以利用到如下的JAVA函數轉化:

public static String fileEncode(String str) {if (str != null) {//這裡是專為檔案寫的轉義方法,涉及檔案操作return str.replaceAll("\\\\", "\").replaceAll("/", "/").replaceAll(":", ":").replaceAll("[*]", "*").replaceAll("[?]", "?").replaceAll("\"", "”").replaceAll(":", ":").replaceAll("<", "<").replaceAll(">", ">").replaceAll("[|]", "|");} else {//防止空,搞成空格return " ";}}
如果你在建立的檔案夾中,中含有\/:*?"<>|,file.mkdirs();只會返回false,不會拋出任何異常,然後不建立檔案夾,因此這個錯誤相當隱蔽。

比如如下的程式:

public class FileMkdirTest {public static void main(String[] args) {File file = new File("d:\\1\\|");if (!file.exists()) {file.mkdirs();}}}
在d:\1中的|檔案夾建立失敗,但Java控制台不返回任何資訊,具體運行結果如:



【Java】利用內建的file.mkdirs();建立檔案夾與file.mkdirs();的注意事項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.