ต่อไปนี้เราจะแสดงการค้นหาไฟล์โดยการระบุประเภทไฟล์ใน Java โดยตัวอย่างเป็นการหาไฟล์ ".jpg" ใน "C:\\users\\nopphanan7\\folder".
package demo.file;
import java.io.*;
public class FindCertainExtension {
private static final String FILE_DIR = "C:\\users\\nopphanan7\\folder";
private static final String FILE_TEXT_EXT = ".jpg";
/**
* @param args
*/
public static void main(String args[]) {
new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT);
}
public void listFile(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if (dir.isDirectory() == false) {
System.out.println("Directory does not exists : " + FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter) == null ? new String[0] : dir
.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FILE_DIR).append(File.separator)
.append(file).toString();
System.out.println("file : " + temp);
}
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
ผลลัพธ์ที่ได้คือ
file : C:\users\nopphanan7\folder\FIO.jpg
file : C:\users\nopphanan7\folder\photo.jpg
file : C:\users\nopphanan7\folder\photo2.jpg
file : C:\users\nopphanan7\folder\the_dark_knight.jpg
file : C:\users\nopphanan7\folder\ubuntu-black-1440x900.jpg
This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
0 comments:
Post a Comment