"Java" takes advantage of its own file.mkdirs (); Create folders and File.mkdirs (); considerations

Source: Internet
Author: User

Using Java's own command File.mkdirs (), you can create a folder directly in the system.

For example, to create a 2 folder under the D:\1 folder, write this:

Import java.io.*;p Ublic class Filemkdirtest {public static void main (string[] args) {File file = new file ("d:\\1\\2");//If D:\1\2 This folder does not exist before creating if (!file.exists ()) {file.mkdirs ();}}}

Java also sees folders as a file,

However, it is worth noting that the folder or file name must not contain: two-directional slash/, colon:, asterisk *, question mark?, quotation marks, left and right angle brackets <>, vertical bar |, you want to use this symbol as a folder or a filename, it is best to convert them to \/:*? "<> |, you can take advantage of the following Java function conversions:

public static string Fileencode (String str) {if (str! = NULL) {//Here is an escape method specifically written for the file, involving the file operation return Str.replaceall ("\\\\", "\"). R Eplaceall ("/", "/"). ReplaceAll (":", ":"). ReplaceAll ("[*]", "*"). ReplaceAll ("[?]", "? "). ReplaceAll (" \ "", "" "). ReplaceAll (": ",": "). ReplaceAll (" < "," ""). ReplaceAll (">", ">"). ReplaceAll ("[|]", "|" );} else {//prevent null, make a space return "";}}
If you are in a new folder that contains \/:*? "<>|,file.mkdirs (); returns false only, does not throw any exceptions, and then does not create folders, so this error is quite covert.

For example, the following programs:

public class Filemkdirtest {public static void main (string[] args) {File file = new file ("d:\\1\\|"); if (!file.exists ()) {file.mkdirs ();}}}
Folder creation failed in D:\1, but the Java console does not return any information, and the results are as follows:



"Java" takes advantage of its own file.mkdirs (); Create folders and File.mkdirs (); considerations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.