我正在尝试从Windows的下载目录中打开csv文件。这是算法:
以下是执行#1和#2(从此link获取)的代码段: 代码段如下:
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;
public class FileSortingTest {
public static void main(String[] args) {
File dir = new File("C:\\Users\\user\\Downloads");
File[] files = dir.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
}
如何将最后更新的文件放入变量中,然后打开文件以使用Excel读取?
答案 0 :(得分:1)
I assume that if your Array is correctly sorted you could do something like this :
File lastUpdatedFile = files[0]
Process process = new ProcessBuilder("C:\\PathToExcel\\Excel.exe",lastUpdatedFile.getAbsolutePath()).start();
答案 1 :(得分:0)
在StackOverflow中探索更多内容以及关于使用Desktop类的link后,我能够使用以下内容:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenAFile2 {
public static void main(String[] args) throws IOException{
String userdir = System.getProperty("user.home");
String dirpath2 = userdir + "\\Downloads";
File fileName = getLatestFilefromDir(dirpath2);
System.out.println(fileName);
File file = fileName;
if(!Desktop.isDesktopSupported()){
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);
if(file.exists()) desktop.open(file);
}
private static File getLatestFilefromDir(String dirPath2){
File dir = new File(dirPath2);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
}