无法使用新file构造函数的Parent和Child参数用Java创建文件



我正在尝试使用Java创建一个文件。我想在我的"文档"目录的子文件夹中创建这个文件。我希望此子文件夹以今天的日期为基础。

我想我知道如何正确使用File类和file.mkdirs()方法,但我想我没有。

这是我所拥有的:

public class FileTest {
private static final String sdfTimestampFormat = "yyyy-MM-dd HH:mm:ss Z";
private static final SimpleDateFormat timestampSDF = new SimpleDateFormat(sdfTimestampFormat);
private static final String sdfDirFormat = "yyyy-MM-dd";
private static final SimpleDateFormat dirSDF = new SimpleDateFormat(sdfDirFormat);
public static void test() throws FileNotFoundException, IOException{
Date rightNow = new Date();
String data = "the quick brown fox jumps over the lazy dog";
String path = System.getProperty("user.home");
String filename = "file.txt";
String directory_name = path + System.getProperty("file.separator") + "Documents" + System.getProperty("file.separator") + dirSDF.format(rightNow);
File file = new File(directory_name, filename);
if(file.mkdirs()){
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}
}
}

正在发生的情况是创建了以下目录

C:Users<username>Documents2018-08-03file.txt

我的印象是,新File构造函数的Parent参数是基本目录,而新File构造函数的Child参数是文件本身。

事实并非如此吗?我是否需要两个File对象,一个用于基本目录,另一个用于文件?

我想要的是:

C:Users<username>Documents2018-08-03file.txt

谢谢。

mkdirs()将为路径中的每个元素创建目录(如果它们不存在(。

因此,您可以使用file.getParentFile().mkdirs()不为file.txt创建目录

编辑:需要考虑的事项

mkdirs()只有在实际创建目录时才返回true。如果它们已经存在或创建它们时出现问题,它将返回false

由于您试图多次运行此程序以将其附加到文本中,因此您的逻辑不会在if-statement中运行

我会把它改成:

boolean created = true;
if(!file.getParentFile().exists()) {
created = file.getParentFile().mkdirs();
}
if (created) {
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}

相关内容

最新更新