一个目录下有10个文件file1.txt
file2.asc
file3.doc
......如何用程序的到所有的文件名称,然后分别处理每个文件?谢谢!

解决方案 »

  1.   

    //看看这个,将文件列成一个树状结构写在文本文件中
    package test;import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.TreeMap;public class TreeTest { /**
     * @param chengzhuo
     */ private static ArrayList filelist = new ArrayList();
    static HashMap hm = new HashMap();
    static int count = 0; public static void main(String[] args) { long a = System.currentTimeMillis();
    String key = null;
    refreshFileList("E:\\tools\\soft\\EditPlus", key);
    System.out.println(System.currentTimeMillis() - a);
    new TreeTest().printAll();
    } public void printAll() {
    TreeMap tm = new TreeMap();
    tm.putAll(hm);
    Iterator it = tm.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry m = (Map.Entry) it.next();
    System.out
    .println("key *" + m.getKey() + "  value*" + m.getValue());

    } write(
    "D:/workspace_new/cloud01/WebContent/richfaces/tree/examples/testTree.properties",
    tm);
    } public static void write(String path, TreeMap hm) {
    String tempStr = new String();
    try {
    File f = new File(path);
    if (f.exists()) {
    System.out.println("文件存在");
    } else {
    System.out.println("文件不存在,正在创建...");
    if (f.createNewFile()) {
    System.out.println("文件创建成功!");
    } else {
    System.out.println("文件创建失败!");
    } } Iterator it = hm.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry m = (Map.Entry) it.next();
    String key = (String) m.getKey();
    tempStr += key.replaceAll(":", ".") + "=" + m.getValue() + "\n";
    // System.out.println("key *" + m.getKey() + "  value*"
    // + m.getValue());
    } BufferedWriter output = new BufferedWriter(new FileWriter(f));
    output.write(tempStr);
    output.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    } public static void refreshFileList(String strPath, String key) {
    File dir = new File(strPath);
    File[] files = dir.listFiles(); if (files == null)
    return; for (int i = 0; i < files.length; i++) { if (key == null) {
    count = i + 1;
    key = count + "";
    } else {
    key = key + ":" + (i + 1);
    }
    if (files[i].isDirectory()) { hm.put(key, files[i].getName());
    System.out.println("key: " + key + "  name: "
    + files[i].getName() + "  dir");
    refreshFileList(files[i].getAbsolutePath(), key); } else { hm.put(key, files[i].getName());
    System.out.println("key: " + key + "  name: "
    + files[i].getName() + "  file");
    String strFileName = files[i].getAbsolutePath().toLowerCase();
    filelist.add(files[i].getAbsolutePath()); }
    if (key != null) {
    String[] keyArray = key.split(":");
    System.out.println("keyLeng ----------------" + keyArray.length
    + "   " + key);
    if (keyArray.length == 1) {
    key = null; } else if (keyArray.length > 1) { String[] array = key.split(":");
    int last = key.lastIndexOf(array[array.length - 1]);
    key = key.substring(0, last - 1);
    }
    }
    }
    }
    }
      

  2.   

    package test;import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.TreeMap;public class TreeTest { /**
     * @param chengzhuo
     */ private static ArrayList filelist = new ArrayList();
    static HashMap hm = new HashMap();
    static int count = 0; public static void main(String[] args) { long a = System.currentTimeMillis();
    String key = null;
    refreshFileList("E:\\tools\\soft\\EditPlus", key);
    System.out.println(System.currentTimeMillis() - a);
    new TreeTest().printAll();
    } public void printAll() {
    TreeMap tm = new TreeMap();
    tm.putAll(hm);
    Iterator it = tm.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry m = (Map.Entry) it.next();
    System.out
    .println("key *" + m.getKey() + "  value*" + m.getValue());

    } write(
    "D:/workspace_new/cloud01/WebContent/richfaces/tree/examples/testTree.properties",
    tm);
    } public static void write(String path, TreeMap hm) {
    String tempStr = new String();
    try {
    File f = new File(path);
    if (f.exists()) {
    System.out.println("文件存在");
    } else {
    System.out.println("文件不存在,正在创建...");
    if (f.createNewFile()) {
    System.out.println("文件创建成功!");
    } else {
    System.out.println("文件创建失败!");
    } } Iterator it = hm.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry m = (Map.Entry) it.next();
    String key = (String) m.getKey();
    tempStr += key.replaceAll(":", ".") + "=" + m.getValue() + "\n";
    // System.out.println("key *" + m.getKey() + "  value*"
    // + m.getValue());
    } BufferedWriter output = new BufferedWriter(new FileWriter(f));
    output.write(tempStr);
    output.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    } public static void refreshFileList(String strPath, String key) {
    File dir = new File(strPath);
    File[] files = dir.listFiles(); if (files == null)
    return; for (int i = 0; i < files.length; i++) { if (key == null) {
    count = i + 1;
    key = count + "";
    } else {
    key = key + ":" + (i + 1);
    }
    if (files[i].isDirectory()) { hm.put(key, files[i].getName());
    System.out.println("key: " + key + "  name: "
    + files[i].getName() + "  dir");
    refreshFileList(files[i].getAbsolutePath(), key); } else { hm.put(key, files[i].getName());
    System.out.println("key: " + key + "  name: "
    + files[i].getName() + "  file");
    String strFileName = files[i].getAbsolutePath().toLowerCase();
    filelist.add(files[i].getAbsolutePath()); }
    if (key != null) {
    String[] keyArray = key.split(":");
    System.out.println("keyLeng ----------------" + keyArray.length
    + "   " + key);
    if (keyArray.length == 1) {
    key = null; } else if (keyArray.length > 1) { String[] array = key.split(":");
    int last = key.lastIndexOf(array[array.length - 1]);
    key = key.substring(0, last - 1);
    }
    }
    }
    }
    }
      

  3.   


    try it now, thanks
      

  4.   

    1.File.listFiles() 对整个目录遍历
    2.得到file的数组,然后循环遍历数组,在getName(),就可以了
      

  5.   

    用一个递归就可以了。
    可以得到文件夹下面所有的文件的名称。
    看代码:import java.io.File;public class FileDirectoryTest
    {
    public static void main(String args[])
    {
    File path = new File("D:\\test\\");
    printFile(path);
    } public static void printFile(File f)
    {
    int i = 0;
    String[] list = f.list(); if (f.isFile())
    System.out.println(f.getName());
    else
    while(f.isDirectory() && i < list.length)
    {
    printFile(new File(f.getPath() + "\\" + list[i]));
    i++;
    }
    }
    }
      

  6.   

    public class ListFile {
      private List list = new ArrayList();
      public static void main(String[] args) {
        List list1 = new ListFile().listFiles("F:/logs");
        for(int i=0;i<list1.size();i++) 
          System.out.println(list1.get(i));
      }
      public List listFiles(String pathname) {
        File file = new File(pathname);
        File[] array = file.listFiles();
        for(int i=0;i<array.length;i++) {
        if(array[i].isFile()) 
          list.add(array[i].getName());   
        if(array[i].isDirectory()) {
          String path = array[i].getAbsolutePath();
          listFiles(path);
        }
      }  
      return list;
      }
    }
      

  7.   

    呵呵,前二天刚刚做过。。写出来参考 一下。
    public class TextClass{
        public void getFileList{String path}{
           File f1 = new File(path);
           File[] fs = f1.FileList();
           for(int i=0;i<fs.length;++i){
              File f2 = fs[i];
              if(f2.isDirectory()){
                 getFileList(f2.getPath());
              }else{
                  String name = f2.getName();
                  //这时候就可以做你想要的操作了;
              }
           }
        }
    }
      

  8.   

    支持十楼,指出两个错误
    1.public void getFileList{String path}{}看一下是否有错
    2.File[] fs = f1.FileList(); 
    api中有这个方法吗??
      

  9.   

    1.判断文件是否存在 File f1 = new File(path); 
    2.File[] fs = f1.FileList();  应该是listFiles() 
    3.递归
      

  10.   

    public File[] listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。 
    如果此抽象路径名不表示一个目录,那么此方法将返回 null。否则返回一个 File 对象数组,每个数组元素对应目录中的每个文件或目录。表示目录本身及其父目录的名称不包括在结果中。得到的每个抽象路径名都是根据此抽象路径名,使用 File(File, String) 构造方法构造的。所以,如果此路径名是绝对路径名,那么得到的每个路径名都是绝对路径名;如果此路径名是相对路径名,那么得到的每个路径名都是相对于同一目录的路径名。 不保证所得数组中的相同字符串将以特定顺序出现,特别是不保证它们按字母顺序出现。 
      

  11.   

    import java.io.*;public class FileTest {
        public static void main(String[] args)
        {
            try
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.print("请输入目录名:");
                String sdir=br.readLine();
                File dir=new File(sdir);
                if(!dir.exists())
                {
                    System.out.println("目录不存在");
                    System.exit(0);
                }
                String[] list=dir.list();
                for(int i=0;i<list.length;i++)
                    System.out.println(list[i]);
                
                System.out.print("给一个文件(或目录)重命名,请输入旧名:");
                String sfile=br.readLine();
                File old=new File(sfile);
                if(!old.exists())
                {
                     System.out.println("不存在");
                    System.exit(0);
                }
                System.out.print("请输入新名:");
                sfile=br.readLine();
                File rname=new File(sfile);
                old.renameTo(rname);
                
                System.out.print("删除一个文件(或目录),请输入文件名:");
                sfile=br.readLine();
                File f=new File(sfile);
                if(!f.exists())
                {
                     System.out.println("不存在");
                      System.exit(0);
                }
                System.out.print("确实要删除这个文件(Y/N)?");
                if(br.readLine().equalsIgnoreCase("Y"))
                {
                    f.delete();
                }
                
                System.out.print("查看一个文件的属性,请输入文件名:");
                sfile=br.readLine();
                File nfile=new File(sfile);
                if(!nfile.exists()||(!nfile.isFile()))
                {
                    System.out.println("文件不存在");
                    System.exit(0);
                }
                System.out.println(nfile.getName()+"in"+nfile.getPath()+"is "+nfile.length()+
                        " bytes"+"\nCan Read:"+nfile.canRead()+"\nCan Write:"+nfile.canWrite());
                
                System.out.print("创建一个目录,请输入目录名:");
                String cdir=br.readLine();
                File dir1=new File(cdir);
                if(dir1.exists())
                {
                    System.out.println("目录已存在!");
                    System.exit(0);
                }           
                
            }
            catch(IOException e)
            {
                System.out.println(e);
            }
        }
    }
      

  12.   

    import java.io.*;public class FileTest {
        public static void main(String[] args)
        {
            try
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                System.out.print("请输入目录名:");
                String sdir=br.readLine();
                File dir=new File(sdir);
                if(!dir.exists())
                {
                    System.out.println("目录不存在");
                    System.exit(0);
                }
                String[] list=dir.list();
                for(int i=0;i<list.length;i++)
                    System.out.println(list[i]);
                
                System.out.print("给一个文件(或目录)重命名,请输入旧名:");
                String sfile=br.readLine();
                File old=new File(sfile);
                if(!old.exists())
                {
                     System.out.println("不存在");
                    System.exit(0);
                }
                System.out.print("请输入新名:");
                sfile=br.readLine();
                File rname=new File(sfile);
                old.renameTo(rname);
                
                System.out.print("删除一个文件(或目录),请输入文件名:");
                sfile=br.readLine();
                File f=new File(sfile);
                if(!f.exists())
                {
                     System.out.println("不存在");
                      System.exit(0);
                }
                System.out.print("确实要删除这个文件(Y/N)?");
                if(br.readLine().equalsIgnoreCase("Y"))
                {
                    f.delete();
                }
                
                System.out.print("查看一个文件的属性,请输入文件名:");
                sfile=br.readLine();
                File nfile=new File(sfile);
                if(!nfile.exists()||(!nfile.isFile()))
                {
                    System.out.println("文件不存在");
                    System.exit(0);
                }
                System.out.println(nfile.getName()+"in"+nfile.getPath()+"is "+nfile.length()+
                        " bytes"+"\nCan Read:"+nfile.canRead()+"\nCan Write:"+nfile.canWrite());
                
                System.out.print("创建一个目录,请输入目录名:");
                String cdir=br.readLine();
                File dir1=new File(cdir);
                if(dir1.exists())
                {
                    System.out.println("目录已存在!");
                    System.exit(0);
                }           
                dir1.mkdirs();//这里加一句,创建目录
            }
            catch(IOException e)
            {
                System.out.println(e);
            }
        }
    }
      

  13.   

    推荐Apache的CommonIO。里面有个FileUtils类。体供了N多操作文件的方法。如:整个目录的拷贝;直接把文件以行读取到List中等等。
      

  14.   

    有那么复杂吗?import java.io.*;
    public class TestDir{
    public static void main(String args[]){
    File f=new File("Test/");
    show(f);
    }

    public static void show(File fi){
    File []file=fi.listFiles();//得到test文件夹列表
    for(int i=0;i<file.length;i++){//循环test文件夹
    if(file[i].isFile()){//如果是文件就打印出来
    System.out.println(file[i].getAbsolutePath());//改一下这个地方这里是打出文件的绝对路径
    }
    if(file[i].isDirectory()){//如果是目录就重新调show方法(递归)
    show(file[i]);
    }
    }
    }
    }
      

  15.   

    有那么复杂吗?import java.io.*;
    public class TestDir{
    public static void main(String args[]){
    File f=new File("Test/");
    show(f);
    }

    public static void show(File fi){
    File []file=fi.listFiles();//得到test文件夹列表
    for(int i=0;i<file.length;i++){//循环test文件夹
    if(file[i].isFile()){//如果是文件就打印出来
    System.out.println(file[i].getAbsolutePath());//改一下这个地方这里是打出文件的绝对路径
    }
    if(file[i].isDirectory()){//如果是目录就重新调show方法(递归)
    show(file[i]);
    }
    }
    }
    }
      

  16.   

     <%@ page import="java.io.*" %>
        <%@ page import="java.util.*" %>
    String path=request.getRealPath("/upload");
    File fi= new File(path);
    File[] file=fi.listFiles();//得到test文件夹列表
    for(int i=0;i<file.length;i++){//循环test文件夹
    int indexname=file[i].getName().indexOf(".",0);
    String filename=file[i].getName().substring(0,indexname);
    %>
    <br>
    <a href="/Struts2/download.action?url=<%=file[i].getName()%>"><%=filename %></a>
    <br>
    <%
    }我是在JSP中实现的..