在java中创建一个目录

Sup*_*tar 2 java file creation filenotfoundexception ioexception

我正在尝试创建一个目录并将文件复制到它.我实现的代码及其输出如下.问题似乎是不言自明的,但我会明确地告诉那些无法分辨的人.

问题


无论我做什么,我似乎无法创建复制文件所需的目标文件.


get是要复制的文件,是要复制到dest的目录.ERR>为清楚起见,添加了行号和" ".我已经注释了我尝试过的其他文件创建方法,但它们都失败了.

115:  private void copyTo(File get, File dest)
116:  {
117:    try
118:    {
119:      dest = new File((dest.getPath().endsWith(File.separator) ? dest.getPath() : dest.getPath() + File.separator) + get.getName());
120:      
121:      java.io.FileInputStream fis = new java.io.FileInputStream(get);
122:      if (dest.exists())
123:        while(!dest.delete());
124:      dest.mkdir();
125://      dest.createNewFile();
126://      java.io.FileWriter w = new java.io.FileWriter(dest);
127://      w.write("");
128:      System.out.println("Writing \"" + get + "\" to \"" + dest + "\"");
129:ERR>  java.io.FileOutputStream fos = new java.io.FileOutputStream(dest);
130:      int b;
131:      do
132:      {
133:        b = fis.read();
134:        fos.write(b);
135:      }while (b != -1);
136:    }
137:    catch (FileNotFoundException ex)
138:    {
139://      System.err.println("404: \"" + get + "\"");
140:      ex.printStackTrace();
141:    }
142:    catch (java.io.IOException ex)
143:    {
144://      System.err.println("IO exception on \"" + get + "\"");
145:      ex.printStackTrace();
146:    }
147:  }
Run Code Online (Sandbox Code Playgroud)

产量


Writing "J:\warehouse.txt" to "J:\backup\warehouse.txt"
java.io.FileNotFoundException: J:\backup\warehouse.txt (The system cannot find the path specified)
        at java.io.FileOutputStream.open(Native Method)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
        at copy.TUI.copyTo(TUI.java:129)
        at copy.TUI.copy(TUI.java:110)
        at copy.TUI.run(TUI.java:102)
        at copy.Main.main(Main.java:37)
Run Code Online (Sandbox Code Playgroud)

Ber*_*ase 6

使用dest.getParentFile().mkdir().这将为您的dest文件创建父目录.如果可能缺少多个父路径元素,您可以使用该mkdirs()方法以递归方式创建所有缺少的目录.