2012-06-25 82 views
0

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

总之,我想要有一个名为“输出”的目录,然后我想在执行我的程序过程中放入不同的文件。

任何人都可以请告诉我如何在java中做到这一点?现在我的下面的代码是在当前的directoy中创建不同的文件。为了我的方便,我想将所有文件放在一个文件夹中。

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"); 

    } 

回答

0

您好您可以使用文件的存在的方法来检查,如果你的目录/文件存在一切准备就绪,

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

0

你最好的答案是看看公用IO库,特别是FileUtils。它应该涵盖大多数事情你需要:

Commons IO Javadoc

2

它支持开箱即用:

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