如何在Java中获取自动生成的文件夹路径以解析文件夹中的文件

3
在Unix中创建一个文件夹路径,例如/data/test/files/2015/05/19。从年份开始,文件夹是自动生成的/data/test/files/$(date +%Y)/$(date +%m)/$(date +%d)
因此,上述文件夹位置内的.txt文件应通过Java代码进行解析并移动到数据库中。
我尝试将该位置解析为2015/05/19,但由于未来会更改,因此尝试在Java中附加当前年/月/日,然后解析特定文件。
//To get current year
String thisYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("thisYear :"+thisYear);
//To get current month
String thisMonth = new SimpleDateFormat("MM").format(new Date());
System.out.println("thisMonth : "+thisMonth);

//To get current date
String thisDay = new SimpleDateFormat("dd").format(new Date());
System.out.println("thisDay : "+thisDay);

File f = new File("\\data\\test\\files\\+"thisYear"+\\+"thisMonth"+\\+"thisDay"+ \\refile.txt");

上述方法不起作用,那么我如何在路径中使用thisYear,thisMonth,thisDay

文件夹分隔符(\)与Unix(/)不同。 - newstackoverflowuser5555
为什么文件路径中需要星号字符? - herry
1
@herry:不是星号,尝试将“thisYear”加粗。 - Bala K
2个回答

2

试一下这个。我认为这个会起作用。

File f = new File("/data/test/files/" + thisYear+ "/" + thisMonth+ "/" +thisDay + "/refile.txt");

1
您可以使用SimpleDateFormat类,例如:
String format = "yyyy/MM/dd".replace( "/" , File.separator );
SimpleDateFormat sdf = new SimpleDateFormat( format );

String pathPrefix = "/data/test/files/".replace( "/" , File.separator );
File f = new File( pathPrefix + sdf.format( new Date() ) + File.separator + "refile.txt" );

记住路径分隔符字符是与文件系统相关的,因此使用 File.separator。如果您不需要“今天”的目录,可以将 new Date() 替换为其他内容。
如果您需要扫描所有日期格式的目录,则需要另外提出问题,但请查看 File.list() 方法。
干杯,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接