gpt4 book ai didi

java - 如何搜索文件?

转载 作者:搜寻专家 更新时间:2023-11-01 01:42:45 24 4
gpt4 key购买 nike

假设用户将输入他们的“ID #:1203103”,然后它会自动创建一个名为 1203103.txt 的文本文件。如何在文件目录中搜索文件名“1203103.txt”?

String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");

最佳答案

你可以试试这个。

import java.io.*;

class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}

希望这对您有所帮助。

关于java - 如何搜索文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com