File path = new File(filePaths);
String[] fileNames = path.list();这样就可以得到所有文件的名称

解决方案 »

  1.   

    楼主不要在这浪费分了。。对你没帮助的实例化一个File对象f后   里面有个方法可以返回File[] 然后迭代这个File[](只要判断其中哪个是目录) 就可以了。多看一下javadoc  那就是最好的帮助~~~就算给你个源程序,帮助也不会太大~~
      

  2.   

    FileViewer.javaimport java.io.File;
    import java.util.Date;
    import java.util.Iterator;
    import java.util.Vector;public class FileViewer{
            File myDir;
            File[] contents;
            Vector vectorList;
            Iterator currentFileView;
            File currentFile;
            String path;
            public FileViewer(){
                    path=new String("");                        
                    vectorList=new Vector();
            }        public FileViewer(String path){
                    this.path=path;
                    vectorList=new Vector();
            }                /**         * 设置浏览的路径        */
            public void setPath(String path){
                    this.path=path;
            }        /***
             * 返回当前目录路径
            */
            public String getDirectory(){
                    return myDir.getPath();
            }
            /**
             * 刷新列表
            */
            public void refreshList(){
                    if(this.path.equals("")) path="c:\\";
                    myDir=new File(path);
                    vectorList.clear();
                    contents =myDir.listFiles();
                    //重新装入路径下文件
                    for(int i=0;i                        vectorList.add(contents[i]);
                    }
                    currentFileView=vectorList.iterator();
            }
            /**
             * 移动当前文件集合的指针指到下一个条目
             * @return 成功返回true,否则false
            */
            public boolean nextFile(){
                    while(currentFileView.hasNext()){
                            currentFile=(File)currentFileView.next();
                            return true;
                    }
                    return false;
            }
            /**
             * 返回当前指向的文件对象的文件名称
            */
            public String getFileName(){
                    return currentFile.getName();
            }        /**
             * 返回当前指向的文件对象的文件尺寸
            */
            public String getFileSize(){
                    return new Long(currentFile.length()).toString();
            }
            /**
             * 返回当前指向的文件对象的最后修改日期
            */        
            public String getFileTimeStamp(){                return new Date(currentFile.lastModified()).toString();
            }        /**
             * 返回当前指向的文件对象是否是一个文件目录
            */
            public boolean getFileType(){
                    return currentFile.isDirectory();
            }
    }
     
    通过setPath()方法设定要浏览的目录(注意如果操作系统为微软操作系统,每个路径分隔符应写成两个斜杠\\),nextFile()方法用来移动列表记录,可以通过getFileName()得到文件或文件夹名称,通过getFileSize()得到文件尺寸,通过getFileTimeStamp()得到文件的最后修改时间,通过getFileType()判断是否是一个文件目录。编写一个test例子测试这个FileViewer类
    test.javaimport java.io.*;public class test{
            public static void main(String[] args){
                    System.out.println("File List");
                    FileViewer f=new FileViewer();
                    f.setPath("d:\\");
                    f.refreshList();
                    while(f.nextFile()){
                            System.out.print(f.getFileName());
                            if(!f.getFileType())
                                    System.out.print("  "+f.getFileSize());
                            else
                                    System.out.print("  ");
                            System.out.print(f.getFileTimeStamp()+"\n");
                    }
            }
    }
      

  3.   

    拿去参考:import java.io.*;
    public class ListFilesAndDirs{
      public static void main(String arg[]){
        getFilesAndDirs(new File("."),0);
      } 
      public static void getFilesAndDirs(File f,int tab){
        File subFiles[]=f.listFiles();//你问的
        int i,j;
        if(subFiles!=null){
          for(i=0,j=0;i<subFiles.length;i++){
            if(subFiles[i].isFile()){
              while (j<tab){
                System.out.print("\t");
                j++;
              }
              j=0;
              System.out.println(subFiles[i].getName());                        
            }       
          }
          for(i=0,j=0;i<subFiles.length;i++){
            if(subFiles[i].isDirectory()){
              while (j<tab){
                System.out.print("\t");
                j++;
              }
              j=0;
              System.out.println("<"+subFiles[i].getName()+">");          
              getFilesAndDirs(subFiles[i],tab+1);      
            }
            
          }
            
        }
      } 
    }
      

  4.   

    package tree;import java.io.File;
    import java.util.Arrays;
    import java.util.EmptyStackException;
    import java.util.Iterator;/**
     * @author Administrator
     *
     * 更改所生成类型注释的模板为
     * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
     */
    public class FileTree extends Tree{

    private String root;
    private File rootDirectroy ;
    public FileTree( String rootDirectroy){
    this.root = rootDirectroy;
    this.rootDirectroy = new File(rootDirectroy);
    }

    public void buildingTree(){
    /**
     * 构建文件树的根节点并将其压入堆栈 
     *  使树的ID号自增
     */
    Node rootNode = new Node(ROOTID,null);
    rootNode.setValue(rootDirectroy);
    stack.push(rootNode);
    ID++;
    /**
     * 
     */
    try{
    while(stack.peek()!=null){
    Node currentNode =(Node)stack.pop();
    treeNodes.add(currentNode);
    convertDate(currentNode);
    }//end while(stack.peek()!=null)
    }catch(EmptyStackException e){
    System.out.println(" stack construt with list end ! ");
    }
    }
    protected void convertDate(Node currentNode){

    File currentFile = (File)currentNode.getValue();
    if(currentFile.isDirectory()){
    File[] files = ((File)currentNode.getValue()).listFiles();
    for(int i=0;i<files.length;i++){
    Node childNode = new Node(ID++,currentNode);
    childNode.setValue(files[i]);
    stack.push(childNode);
    }
    }//end if(currentFile.isDirectory())
    }

    public static void main(String[] args)
    {
    Tree fileTree = new FileTree("E:\\Cavaj Java Decompiler");
    fileTree.buildingTree();
    Iterator iterator = fileTree.getTreeNodes();
    int count = 0;
    while(iterator.hasNext()){
    count++;
    Node node = (Node)iterator.next();
    for(int i=0;i<node.getLevel();i++)
    {
    System.out.print(" ");
    }
    System.out.println(((File)node.getValue()).getName());
    }
    System.out.println(" 共计 : "+count+" 文件");
    }
    }
      

  5.   

    package tree;import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Iterator;/**
     * @author Administrator
     *
     * 更改所生成类型注释的模板为
     * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
     */
    public class Node
    {
    /**
     * 节点的ID
     */
    private int id ;
    /**
     * 节点的父节点
     */
    private Node parentNode;
    /**
     * 节点所在的层
     */
    private int level=0;
    /**
     * 节点的存储数值
     */
    private Object value;
    /**
     * 子节点的集合
     */
    private ArrayList children = new ArrayList();

    public Node(int id,Node parentNode){
    this.id = id;
    this.parentNode = parentNode;
    if(this.parentNode!=null)
    {
    parentNode.children.add(this);
    this.level = parentNode.getLevel()+1;
    }else{
    level=1;
    }
    }
    /**
     * 判断节点是否是叶子节点
     */
    public boolean isLeaf(){
    return children.isEmpty();
    }
    /**
     * 
     * @param childIndex
     * @return
     */
    public boolean hasChirlder(){
    return getChildren().hasNext();
    }
    /**
     * 根据子节点的序号查询子节点
     * @param childIndex
     * @return
     */
    public Node getChildAt(int childIndex)
    {
    Node node = null;
    int count = -1;
    while(getChildren().hasNext()){

    node = (Node)getChildren().next();
    count++;
    if(count == childIndex)
    {
    // System.out.println("fined childIndex :: "+node.getId());
    return node;
    }
    }
    return node;
    }
    /**
     * 获得子节点的个数
     * @return
     */
    public int getChildCount(){
    return children.size();
    }
    /**
     * 根据子节点获得子节点的序号索引
     * @param node
     * @return
     */
    public int getIndex(Node node){

    int index = -1;
    Node nodeIndex = null;
    Comparator comparamtor = new NodeComparator();
    while(getChildren().hasNext()){
    nodeIndex = (Node)getChildren().next();
    if(comparamtor.compare(nodeIndex,node)==0){
    index = nodeIndex.getId();
    break;
    }

    }
    return index;
    }
    /**
     * 获得此节点的兄弟节点
     * @param args
     */
    public Iterator getBrothers(){

    ArrayList brothers = new ArrayList();
    Comparator comparamtor = new NodeComparator();
    Node currentNode = null;

    while(parentNode.getChildren().hasNext()){
    currentNode = (Node)parentNode.getChildren().next();
    if(comparamtor.compare(currentNode,this)!=0){
    brothers.add(currentNode);
    }
    }
    return brothers.iterator();
    }
    /**
     * 
     * @param args
     */
    public Node getPreviousBrother(){

    Node prevoiusNode = null;
    Node currentNode = null;
    Comparator comparamtor = new NodeComparator();
    while(parentNode.getChildren().hasNext()){
    currentNode = (Node)parentNode.getChildren().next();
    if(comparamtor.compare(currentNode,this)==0){
    break;
    }else{
    prevoiusNode = currentNode;
    }
    }
    return prevoiusNode;
    }
    public static void main(String[] args)
    {

    }
    /**
     * @return
     */
    public int getLevel()
    {
    return level;
    } /**
     * 得到子节点的迭代
     * @return
     */
    public Iterator getChildren()
    {
    return children.iterator();
    } /**
     * @return
     */
    public int getId()
    {
    return id;
    } /**
     * @return
     */
    public Node getParentNode()
    {
    return parentNode;
    } /**
     * @return
     */
    public Object getValue()
    {
    return value;
    }
    /**
     * @param object
     */
    public void setValue(Object object)
    {
    value = object;
    }}
      

  6.   

    package tree;import java.util.Stack;
    import java.util.ArrayList;
    import java.util.Iterator;/**
     * @author Administrator
     *
     * 更改所生成类型注释的模板为
     * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
     */
    public abstract class Tree
    {
    public static final int ROOTID = 0;
    protected int ID = 0 ;
    protected ArrayList treeNodes = new ArrayList(); 

    protected Stack stack =new Stack();
    protected abstract void convertDate(Node currentNode);
    public abstract void buildingTree();

    public static void main(String[] args)
    {
    }
    public Iterator getTreeNodes(){
    return treeNodes.iterator();
    }
    }
      

  7.   

    public String[] getFiles(String filePath){
    File reqFile = new File(filePath);
    String reqPath = reqFile.getPath();
    if (reqFile.isDirectory()){
    String [] fileArr = reqFile.list(new XMLFilenameFilter());
    return fileArr;
    }
    return null;
    }class XMLFilenameFilter implements FilenameFilter
    {
    public boolean  accept(File dir,String name){
    return true;
    }
    }
      

  8.   

    楼上的几个,干嘛呢,养懒汉呐?!尤其是FrankTong(彤瞳)这位老兄,忒令人讨厌了,原本只要一句File.list()的代码话,加上几句解释的,你弄了这么多代码,而且绝大部分是和楼主的问题的关键部分毫无关系,人家看得懂吗
      

  9.   

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.DateFormat;
    import java.util.Date;public class FileLister extends Frame implements ActionListener, ItemListener {
        private List list;
        private TextField details;
        private Panel buttons;
        private Button up, close;
        private File currentDir;
        private FilenameFilter filter;
        private String[] files;
        private DateFormat dateFormatter =
              DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
        
        public FileLister(String directory, FilenameFilter filter) { 
            super("File Lister");
            this.filter = filter;
            
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { dispose(); }
        });        list = new List(12, false);
            list.setFont(new Font("MonoSpaced", Font.PLAIN, 14));
            list.addActionListener(this);
            list.addItemListener(this);
            
            details = new TextField();
            details.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
            details.setEditable(false);        buttons = new Panel();
            buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 15, 5));
            buttons.setFont(new Font("SansSerif", Font.BOLD, 14));        up = new Button("Up a Directory");
            close = new Button("Close");
            up.addActionListener(this);
            close.addActionListener(this);        buttons.add(up);
            buttons.add(close);
            
            this.add(list, "Center");
            this.add(details, "North");
            this.add(buttons, "South");
            this.setSize(500, 350);
            
            listDirectory(directory);
        }
        
        public void listDirectory(String directory) {
            File dir = new File(directory);
            if (!dir.isDirectory()) 
               throw new IllegalArgumentException("FileLister: no such directory");        files = dir.list(filter);         java.util.Arrays.sort(files);

            list.removeAll();
            list.add("[Up to Parent Directory]");  // A special case entry
            for(int i = 0; i < files.length; i++) list.add(files[i]);
            
            this.setTitle(directory);
            details.setText(directory);

            currentDir = dir;
        }
        
        public void itemStateChanged(ItemEvent e) {
            int i = list.getSelectedIndex() - 1;
            if (i < 0) return;
            String filename = files[i];
            File f = new File(currentDir, filename);
            if (!f.exists())
                throw new IllegalArgumentException("FileLister: " +
           "no such file or directory");        String info = filename;
            if (f.isDirectory()) info += File.separator;
            info += " " + f.length() + " bytes ";
            info += dateFormatter.format(new java.util.Date(f.lastModified()));
            if (f.canRead()) info += " Read";
            if (f.canWrite()) info += " Write";

            details.setText(info);
        }
        
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == close) this.dispose();
            else if (e.getSource() == up) { up(); }
            else if (e.getSource() == list) {
                int i = list.getSelectedIndex();
                if (i == 0) up();
                else {
                    String name = files[i-1]; 
                    File f = new File(currentDir, name);
                    String fullname = f.getAbsolutePath();
                    if (f.isDirectory()) listDirectory(fullname);
                    else new FileViewer(fullname).show();
                }
            }
        }
        
        protected void up() {
            String parent = currentDir.getParent();
            if (parent == null) return;
            listDirectory(parent);
        }
        
        public static void usage() {
            System.out.println("Usage: java FileLister [directory_name] " + 
       "[-e file_extension]");
            System.exit(0);
        }
        
        public static void main(String args[]) throws IOException {
            FileLister f;
            FilenameFilter filter = null;
            String directory = null;
            
            for(int i = 0; i < args.length; i++) {
                if (args[i].equals("-e")) {
                    if (++i >= args.length) usage();
                    final String suffix = args[i];                filter = new FilenameFilter() {
    public boolean accept(File dir, String name) {
        if (name.endsWith(suffix)) return true;
        else return (new File(dir, name)).isDirectory();
    }
        };
                }
                else {
                    if (directory != null) usage();
                    else directory = args[i];
                }
            }
            
            if (directory == null) directory = System.getProperty("user.dir");
            f = new FileLister(directory, filter);
            f.addWindowListener(new WindowAdapter() {
                public void windowClosed(WindowEvent e) { System.exit(0); }
            });
            f.show();
        }
    }书上的范例..自己拿去参考吧