2013年9月26日星期四

Novice Help File (File parent, String child) and separator separator Use

Code is as follows :
import java.io. *;
public class IoTest {
public static void main (String [] args) throws Exception {
File parent = new File ("D:");
String child = "1" + File.separator + "1.txt";
File f = new File (parent, child);
f.createNewFile ();
}

}
I think the D drive to create a one folder, and then build a 1.txt file in there , why the show :
Exception in thread "main" java.io.IOException: system can not find the path specified.
at java.io.WinNTFileSystem.createFileExclusively (Native Method)
at java.io.File.createNewFile (File.java: 883)
at a.IoTest.main (IoTest.java: 9)
Seek expert to explain , very grateful ! !
------ Solution ---------------------------------------- ----
File root = new File("D:");
File path = new File(root,"1");
if(!path.exists()) path.mkdirs();
File file = new File(path,"1.txt");
boolean success = file.createNewFile();

------ Solution ------------------------------ --------------
ah , was not aware that reference 3rd floor huntor way you can, call mkdirs ()

------ For reference only ---------------------------------- -----
can be changed to the following

import java.io.*;
public class IoTest {
    public static void main(String[] args) throws Exception {
        File parent = new File("D:");
        String child =File.separator+"1.txt";
        File f = new File(parent, child);
        f.createNewFile();
    }

}

------ For reference only ----------------------------------- ----
your original
String child = "1" + File.separator + "1.txt";
File f = new File (parent, child);
two lines of code , splicing out of the path is not d: \ 1.txt is d: 1 \ 1.txt so I can not find the path specified
------ For reference only ---- -----------------------------------
first, thank you, but I would like to D drive create a folder as a folder name , and then build on the inside 1.txt file .
------ For reference only -------------------------------------- -
reason is a directory does not exist .
need for directory judgment , if necessary, create the required directories.

没有评论:

发表评论