【Java】利用自帶的file.mkdirs()建立資料夾與file.mkdirs()的注意事項
阿新 • • 發佈:2019-02-10
利用Java的自帶命令file.mkdirs();是可以直接在系統建立資料夾的。
比如在d:\1資料夾下建立一個2的資料夾,則這樣寫:
- import java.io.*;
- publicclass FileMkdirTest {
- publicstaticvoid main(String[] args) {
- File file = new File("d:\\1\\2");
- //如果d:\1\2這個資料夾不存在,才建立
- if (!file.exists()) {
- file.mkdirs();
- }
- }
- }
Java把資料夾也視作一個file,
但值得注意的是,在資料夾或檔名中不得含有:兩個方向的斜槓\/、冒號:、星號*、問號?、引號"、左右尖括號<>、豎槓|,你要使用這個符號作為資料夾或檔名稱,最好把他們轉化成全形\/:*?"<>|,可以利用到如下的JAVA函式轉化:
- publicstatic String fileEncode(String str) {
- if (str != null) {
- //這裡是專為檔案寫的轉義方法,涉及檔案操作
- return str
- .replaceAll("\\\\", "\")
- .replaceAll("/", "/")
- .replaceAll(":", ":")
- .replaceAll("[*]", "*")
- .replaceAll("[?]", "?")
- .replaceAll("\"", "”")
- .replaceAll(":", ":")
- .replaceAll("<", "<")
- .replaceAll(">"
- .replaceAll("[|]", "|");
- } else {
- //防止空,搞成空格
- return" ";
- }
- }
比如如下的程式:
- publicclass FileMkdirTest {
- publicstaticvoid main(String[] args) {
- File file = new File("d:\\1\\|");
- if (!file.exists()) {
- file.mkdirs();
- }
- }
- }