我一直试图找出一种基本上在文件夹中搜索.txt文件的方法(文本文件的名称基于用户输入),然后吐出该文本文件的内容。我如何通过Java.io做到这一点?
到目前为止我做了什么
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class searchDemo {
public static void main(String[] args) throws FileNotFoundException{
Scanner keyboard = new Scanner(System.in);
System.out.println("Who would you want to search for?");
String name = keyboard.nextLine();
File dir = new File("/Users/john/Documents/workspace/Axis Powers/users");
Scanner scan = new Scanner("/Users/john/Documents/workspace/Axis Powers/users");
String nameTweets = scan.nextLine();
for(File file : dir.listFiles()){
if(file.isFile() && nameTweets.equalsIgnoreCase(name) && nameTweets.endsWith(".txt")){
System.out.println(name);
System.out.println(nameTweets);
/**
I was getting bugs at this time so I printed the
user input first and then the ".txt" file version of
the user input to see what was printing and it
obviously wasn't what I wanted it to do
**/
}
}
}
}
以下是我给出的任务:允许用户搜索某个人的姓名,如果该人的姓名存在于(。文件中)的.txt版本中,那么它会打印出来内容.txt文件
例如:如果一个人搜索了#34; John Legend"在一个文件中有一个名为" John Legend.txt"的文件,然后它将打印出" John Legend.txt"的内容。文件
答案 0 :(得分:0)
您在此处显示的代码不会进入if子句,因为nameTweets
始终为"/Users/john/Documents/workspace/Axis Powers/users"
,因此nameTweets.equalsIgnoreCase(name)
将为false。
为了让您的代码正常运行,我会删除您的Scanner scan
,并使用listFiles()代替,以便获取目录中的所有文件。之后,如果条件验证,您只需阅读该文件(例如使用BufferedReader)并打印出来。
下面我提供了一个可以达到你想要的代码块。
完整代码
package testsplit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Fraction {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Who would you want to search for?");
String name = keyboard.nextLine();
name += ".txt";
keyboard.close();
File dir = new File("/Users/john/Documents/workspace/Axis Powers/users");
File[] listOfFiles = dir.listFiles();
String filename, line;
for(File file : listOfFiles) {
filename = file.getName();
if(file.isFile() && filename.equalsIgnoreCase(name) && filename.endsWith(".txt") ){
try {
BufferedReader br = new BufferedReader(new FileReader(dir+"/"+filename));
while( (line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
其他笔记