当前位置:编程学习 > JAVA >>

JAVA:根据txt的名字规律读取txt文档.

在我的D盘有个文件夹名字叫: txt库. 文件夹里面有2个txt文档(20120709.txt 和 20120710.txt). 我想写个程式,读完了20120709.txt后,接着继续读取20120710.txt; 单独读取一个txt文档的方法我写好了.想在这个基础上改动下,让它可以根据txt的命名顺序依次全部读完,请大侠们参考下我的代码,帮忙写个循环读取的.我的知识有限,刚学这个,好多都不懂.昨天弄了一天没有弄好.
public static void main(String[] args)throws IOException {
  // TODO Auto-generated method stub
  BufferedReader bufferedReader = null;
  PrintWriter printWriter = null;  
  try{
   bufferedReader = new BufferedReader(new FileReader("D:\\txt库\\20120709.txt")); 
   String l; 
   while ((l = bufferedReader.readLine()) != null) {
    System.out.println(l);
   }
  } finally {
   if (bufferedReader != null) {
    bufferedReader.close();
   }
   if (printWriter != null) {
    printWriter.close();
   }
  }
 } --------------------编程问答-------------------- 有没有牛人飘过.....帮忙哇 --------------------编程问答--------------------
import java.io.File;
public class Test {
 public static void main(String[] args) throws Exception {
  //递归显示C盘下所有文件夹及其中文件
  File root = new File("c:");
  showAllFiles(root);
 }
 
 final static void showAllFiles(File dir) throws Exception{
  File[] fs = dir.listFiles();
  for(int i=0; i<fs.length; i++){
   System.out.println(fs[i].getAbsolutePath());
   if(fs[i].isDirectory()){
    try{
     showAllFiles(fs[i]);
    }catch(Exception e){}
   }
  }
 }
}

去遍历你当前文件夹下的所有文件就OK了啊,这个是个例子,你参考一下嘛 --------------------编程问答-------------------- public static void main(String[] args)throws IOException {
   // TODO Auto-generated method stub
   BufferedReader bufferedReader = null;
   PrintWriter printWriter = null;  
    for(int i=20120709;i<=20120710;i++){
   try{
    String path="D:\\txt库\\"+i+".txt";
    bufferedReader = new BufferedReader(new FileReader(path)); 
    String l; 
    while ((l = bufferedReader.readLine()) != null) {
     System.out.println(l);
    }
   } finally {
    if (bufferedReader != null) {
     bufferedReader.close();
    }
    if (printWriter != null) {
     printWriter.close();
    }
   }
  } 
我后来想下就这样写了.但是奇怪的是它只显示出后面的20100710.txt的文档内容. 我另外建了个文件夹,创建了2个小的txt文档,最终显示了2个小txt文档的内容. 这一点我有点不明白.
补充:Java ,  Eclipse
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,