我正在處理一項自動化任務,其中下載了一個檔案,我必須提取該下載檔案的路徑以及名稱(我知道該檔案將下載到Downloads檔案夾中,但我只想要最新下載檔案的路徑)。最終,我想獲取擴展名。但是只有當路徑可用時我才能獲取擴展名,請幫助我提取路徑。
uj5u.com熱心網友回復:
這應該做的作業:
package foo;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Bar {
public static File getNewestFileFromDir(File dir) throws IOException {
File newestFile = null;
Date newestCreationDate = null;
File[] files = dir.listFiles(File::isFile);
for (File file: files) {
Path filePath = file.toPath();
BasicFileAttributes attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
long milliseconds = attributes.creationTime().to(TimeUnit.MILLISECONDS);
if ((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE)) {
Date creationDate = new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));
if (newestCreationDate != null) {
if (creationDate.after(newestCreationDate)) {
newestCreationDate = creationDate;
newestFile = file;
}
}
}
}
return newestFile;
}
public static String getFileExtension(File file) {
String extension = "";
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i 1).toLowerCase();
}
return extension;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439672.html
上一篇:如何設定VSCode路徑,以便它為我的RubyonRails專案選擇我的rufo擴展?
下一篇:無法從下拉選單中讀取選項名稱
