Java-讀取某個目錄下所有檔案、資料夾和3種從檔案路徑中獲取檔名的方法
阿新 • • 發佈:2019-01-20
1 讀取某個目錄下所有檔案、資料夾
public static ArrayList<String> getFiles(String path) {
ArrayList<String> files = new ArrayList<String>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
// System.out.println("文 件:" + tempList[i]);
files.add(tempList[i].toString());
}
if (tempList[i].isDirectory()) {
// System.out.println("資料夾:" + tempList[i]);
}
}
return files;
}
2 3種從檔案路徑中獲取檔名的方法
package test;
import java.io.File;
public class FileName {
/**
* @param args
*/
public static void main(String[] args) {
// 舉例:
String fName =" G:\\Java_Source\\navigation_tigra_menu\\demo1\\img\\lev1_arrow.gif ";
// 方法一:
File tempFile =new File( fName.trim());
String fileName = tempFile.getName();
System.out.println("fileName = " + fileName);
// 方法二:
String fName = fName.trim();
String fileName = fName.substring(fName.lastIndexOf("/")+1);
//或者
String fileName = fName.substring(fName.lastIndexOf("\\")+1);
System.out.println("fileName = " + fileName);
// 方法三:
String fName = fName.trim();
String temp[] = fName.split("\\\\"); /**split裡面必須是正則表示式,"\\"的作用是對字串轉義*/
String fileName = temp[temp.length-1];
System.out.println("fileName = " + fileName);
}
}