如何使用Java查找文件格式(假设.txt文件,.java文件,.class文件,.zip文件在我的目录中)?
我只需要.txt文件是正文提供的解决方案,它可能会有所帮助。
public class a {
public static void main(String[] ar) {
File f = new File("D:\\")
file[] = f.listFiles();
if (file.isFile && file is txt) {
}
}
}
答案 0 :(得分:2)
使用File#listFiles(FilenameFilter)代替File#listFiles():
f.listFiles(new FilenameFilter() {
private Pattern pattern = Pattern.compile(".*\\.txt");
@Override
public boolean accept(File dir, String name) {
return pattern.matcher(name).matches();
}
});
答案 1 :(得分:1)
如果我确实理解你,你想要找到文件扩展名,这里是我使用swing worker为你制作的示例应用程序,你现在可以使用你在程序中定义的特定文件扩展名扫描整个计算机,目前它找到了html,txt和pdf你可以修改它。
Here is the entire project package
创建扫描工作者类如下所示,使用IDE修复导入
public class ScanWorker extends SwingWorker<Void, String> {
ResultFrame helperv;
int finalTotal = 0;
String str3;
public String status;
public ScanWorker(ResultFrame x) {
finalTotal = 0;
helperv = x;
helperv.jTarea.setText("");
}
@Override
protected Void doInBackground() throws Exception {
helperv.jTarea.replaceSelection("Scanning..." + "\n");
Thread.sleep(100);
callMainScan();
return null;
}
@Override
protected void process(List<String> chunks) {
for (String str : chunks) {
helperv.jTarea.append(str);
helperv.scanlabel.setText(str);
}
}
@Override
protected void done() {
helperv.scanlabel.setText("Total Number of Files Matched: " + Integer.toString(finalTotal));
}
private void callMainScan() throws IOException {
String[] myStringArray = new String[3];
myStringArray[0] = "*.txt";
myStringArray[1] = "*.html";
myStringArray[2] = "*.pdf";
File[] paths;
paths = File.listRoots();
try {
for (File path : paths) {
String str = path.toString();
String slash = "\\";
String s = new StringBuilder(str).append(slash).toString();
Path startingDir = Paths.get(s);
for (String stre : myStringArray) {
String pattern = stre;
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
}
} catch (IOException e) {
System.out.println("Exception occured");
}
}
public class Finder
extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern) {
matcher = FileSystems.getDefault()
.getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
str3 = file.toString();
publish(str3 + "\n");
}
}
// Prints the total number of
// matches to standard out.
void done() {
// System.out.println("Matched: "
// + numMatches);
finalTotal = finalTotal + numMatches;
}
// Invoke the pattern matching
// method on each file.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
find(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
// System.err.println(exc);
return CONTINUE;
}
}
}
扫描按钮操作
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Thread(new Runnable() {
@Override
public void run() {
sw = new ScanWorker(ResultFrame.this);
sw.execute();
}
}).start();
}
答案 2 :(得分:0)
试试这个 -
public static String getExtension(File file) {
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0) {
return fileName.substring(i + 1);
}
return null;
}
public static void main(String[] arr) {
File f = new File("D:\\");
File files[] = f.listFiles();
for (File file : files) {
if (file.isFile()) {
if ("txt".equals(getExtension(file))) {
System.out.println(file.getName()+" is a text file");
}
}
}
}
答案 3 :(得分:0)
你可以使用File.listFiles(FilenameFilter)
;像这样:
File[] files = f.listFiles((File dir, String name) -> name.endsWith(".txt"));
答案 4 :(得分:0)
你可以试试这个。
String directory = "c:";
File file = new File(directory);
if (file.isDirectory()) {
File[] files = file.listFiles();
System.out.println(files.length);
for (File innerFiles : files) {
String fileName = innerFiles.getName();
if (fileName.contains(".") &&
(fileName.substring(fileName.lastIndexOf("."), fileName.length())
.equalsIgnoreCase(".txt"))
System.out.println(fileName);
}
}