【问题标题】:creating a directory and then creating file inside it创建一个目录,然后在其中创建文件
【发布时间】:2012-06-26 15:01:01
【问题描述】:

我想为一个名为“f”的文件创建一个 ouputStreamWriter 对象,说“out”。我希望这个文件 f 在名为“输出”的目录或文件夹中创建。如果目录“输出”不存在,那么它应该创建它,如果已经存在,那么它应该在该目录中创建文件“f”。

简而言之,我希望有一个名为“输出”的目录,然后我想在我的程序执行期间将不同的文件放入其中。

谁能告诉我如何在java中做到这一点?现在我的以下代码正在当前目录中创建不同的文件。为了方便起见,我想将所有文件放在一个文件夹中。

public Dump(String outputFile) throws IOException {
        final FileOutputStream fos = new FileOutputStream(outputFile + "gz.xml");
        final GZIPOutputStream gzfos = new GZIPOutputStream(fos);
        out = new OutputStreamWriter(new BufferedOutputStream(gzfos), "UTF-8");

    }

【问题讨论】:

    标签: java file-io directory objectoutputstream


    【解决方案1】:

    支持开箱即用:

    final File f = new File("dir/file.txt");
    f.getParentFile().mkdirs();
    f.createNewFile();
    

    【讨论】:

      【解决方案2】:

      您好,您可以在文件上使用exists方法来检查您的目录/文件是否已准备就绪,

      File myOutputDir = new File("path");
      
      if(!myOutputDir.exists())
           myOutputDir.mkdir(); //Returns a boolean if you want to check it was successful.
      //Continue with your code the directory should now exist if it did not before.
      

      干杯,

      E

      【讨论】:

        【解决方案3】:

        您最好的答案是查看 commons IO 库,尤其是 FileUtils。它应该涵盖您需要的大部分内容:

        Commons IO Javadoc

        【讨论】:

          猜你喜欢
          • 2015-05-10
          • 2015-03-30
          • 1970-01-01
          • 2014-04-26
          • 2015-03-03
          • 1970-01-01
          • 2017-11-10
          • 1970-01-01
          相关资源
          最近更新 更多