2011-03-31 29 views
0

使程序从文件夹中检索.txt文件。每个.txt文件包含1或2行字。我从文件夹中获得每个.txt文件的每个文件名的输出:输出.txt文件中的每个字符串

Donatello 
Galileo 
Leonardo 
Michael 
Rafael 

ex。代码我到目前为止:

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

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

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

     for(File person : names){ 
      int index = person.getName().lastIndexOf("."); 
      if(index>0&& index <= person.getName().length()-2){ 
       System.out.println(person.getName().substring(0, index)); 
      } 
     } 
    } 
} 

这都是文件名,但那不是我想成为输出。我想要的输出是:

Donatello 2 
Hi 
Hello 
Galileo 2 
Fine 
Thanks 
Leonardo 1 
Hi 
Michael 1 
Hello 
Rafael 1 
Hi 

说明:上面给出的示例输出例如, Donatello 2,空格后面的数字2和名称Donatello,2对应于文件名Donatello.txt内的单词数量。 2因为有两行文字。我希望你明白我的观点。

任何帮助将非常感激。谢谢你...

+0

[输出目录中多个.txt文件中的字符串]的可能重复(http://stackoverflow.com/questions/5481534/output-the-strings-inside-of-multiple-txt-files-in -a-directory) – 2011-03-31 02:41:44

回答

0

最后,我明白了你的观点。 多纳泰罗(文件名)2(含行号) 嗨 你好 (上面两行是在Donatello.txt内容,右

解决方案:

如果文件大小最多为两行,你可以产生一个新的类,以满足您的要求。

class FileInfo { 
String fileName; 
int lineNum; 
String[] content; 
} 

然后逐行读取填写的信息为您的FileInfo文件中的行最后,打印出你需要的所有信息

希望得到这个帮助。

+0

是的,这正是我的观点。谢谢你的方式。我会尝试你的建议。 – 2011-03-31 03:21:04

0

我建议你把你的代码分解成方法。例如,写,需要一个File作为参数并返回线的在该文件中的数的方法:

public int countLines(File f) { 
    ... 
} 

然后,采用一个File和写入它的内容到System.out的方法:

public void writeContents(File f) { 
    ... 
} 

而这需要一个File,并返回它的名字的方法:

public String getName(File f) { 
    ... 
} 

现在,您可以从日撰写程序有三种功能和一些胶水代码:

public void processFiles(File[] files) { 
    for (File file : files) { 
     // Print info for this file using the three functions above 
     ... 
    } 
} 

这通常是编程的好方法。如果问题很难,那就试着把它分成更小的块。

希望有所帮助。

+0

谢谢cameron,我会试试这个。 – 2011-03-31 03:21:56

相关问题