2011-03-30 33 views
0

我有一个文件夹,其文件名是:“名称列表”。在那个文件夹里我有一个5个“.txt”文件文件,每个文件文件名都是一个人的名字。在一个目录中输出多个.txt文件中的字符串

我想检索五个文档并在每个文档中显示字符串。我该怎么做呢?我尝试这样做:

import java.io.*; 
import java.util.*; 

public class Liarliar { 
    public static void main(String args[])throws IOException{ 

     File Galileo = new File("C:\\List of names\\Galileo.txt"); 
     File Leonardo = new File("C:\\List of names\\Leonardo.txt"); 
     File Rafael = new File("C:\\List of names\\Rafael.txt"); 
     File Donatello = new File("C:\\List of names\\Donatello.txt"); 
     File Michael = new File("C:\\List of names\\Michael.txt"); 
     FileInputStream fis = null; 
     BufferedInputStream bis = null; 
     DataInputStream dis = null; 

     try{ 
      System.out.println("Enter a number list of names:"); 
      Scanner scanner = new Scanner(System.in); 
      int input = scanner.nextInt(); 

     }catch(FileNotFoundException e){ 
     }catch(IOException e){ 
     } 
    } 
} 

预先感谢某人的时间...

回答

0

不需要以下行,因为他们是为了采取从用户的输入。

System.out.println("Enter a number list of names:");    
Scanner scanner = new Scanner(System.in);    
int input = scanner.nextInt(); 

相反,您需要使用FileInputStream或FileReader逐个读取文件。有关如何从文件读取数据的示例,请参阅here。为您的每个文件执行此操作。

1

对于像Galileo.txt这样的单个文件的名字来说,这将更加通用。您可以创建代表目录下的文件,然后调用listFiles让所有的目录中的文件,就像

File nameFile = new File(""C:\\List of names"); 
File[] personFiles = nameFile.listFiles(); 

然后你可以遍历这个文件阵列,并打开依次每个文件,读取其中的内容,就像

for (File person : personFiles) { 
    showFileDetails(person); 
} 

其中showFileDetails是您为打开文件和显示信息而编写的单独方法。

相关问题