簡體   English   中英

如何在java中獲取自動生成的文件夾路徑以解析文件夾中的文件

[英]How to get autogenerated folder path in java to parse files from a folder

在Unix中創建了一個像/data/test/files/2015/05/19這樣的文件夾路徑。 從年份開始,文件夾自動生成/data/test/files/$(date +%Y)/$(date +%m)/$(date +%d)

所以上面文件夾位置內的.txt文件應該通過Java代碼解析並移動到DB。

我試圖解析該位置,因為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所以如何使用thisYear,thisMonth,thisDay in path?

試試這個。 我覺得這很有效。

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

您可以使用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用法。 如果您不在“todays”目錄之后,也可以用其他東西替換new Date()

如果您需要掃描所有日期格式的目錄,這是另一個問題的另一個問題,但請查看File.list()方法。

干杯,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM