我是学Java的,最近面试的时候,碰到一个这样的题,由于本人是刚入门的,所以搞不定,就贴到这里来,希望能得到大虾们的指点,不胜感激! 题目:(用Java实现)     写一段代码完成C盘下的文件的排序,打印功能按文件修改的时间进行排序,最近修改的放在最上面? 

解决方案 »

  1.   


    import java.io.*;
    import java.text.SimpleDateFormat;
    public class Test {
    public static void main(String[] args) {
    File f=new File("c:\\");
    File[] ff=f.listFiles();
    for(int i=0;i<ff.length;i++){
    for(int j=i+1;j<ff.length;j++){
    if(ff[i].lastModified()<ff[j].lastModified()){
    File temp=ff[i];
    ff[i]=ff[j];
    ff[j]=temp;
    }
    }
    }
    for(int i=0;i<ff.length;i++){
    System.out.println(ff[i].toString()+" 最后修改日期:"+getLastTime(ff[i].lastModified()));
    }
    }
    static String getLastTime(long time){
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
    return sdf.format(time);
    }
    }这种题不用IDE,真的很难写啊,除非平时经常做这方面的东西
      

  2.   

    import java.io.File;
    import java.io.IOException;
    public class FindDectory
    {
    File[] file;
    public void FindFiles(String str) throws IOException
    {
    File pathName = new File(str);
    String[] fileNames = pathName.list();
        file = new File[fileNames.length];
        
        for (int i = 0; i < fileNames.length; i++)
    {
    File f = new File(pathName.getPath(), fileNames[i]);
    file[i] = f;
    }
        file = this.sort(file);
        this.print(file);
    }

    public void print(File[] f) throws IOException
    {
    for(File t : f)
    System.out.println(t.getCanonicalPath() +" "+ t.lastModified());
    }

    public File[] sort(File[] f)
    {
    for(int j = 1; j < f.length; j++)
    for(int i = 0; i < f.length - j; i++)
    {
    if(f[i].lastModified() > f[i+1].lastModified())
    {
    File t ;
    t = f[i];
    f[i] = f[i+1];
    f[i+1] = t;
    }
    }

    return f;
    }

    public static void main(String[] a) throws IOException
    {
    new FindDectory() .FindFiles("c:\\");
    }
    }
      

  3.   

    上次写的太烦了
    import java.io.File;
    import java.io.IOException;
    public class FindDectory
    {
    File[] file;
    public void FindFiles(String str) throws IOException
    {
    File pathName = new File(str);
    file = pathName.listFiles();
        file = this.sort(file);
        this.print(file);
    }

    public void print(File[] f) throws IOException
    {
    for(File t : f)
    System.out.println(t.getCanonicalPath());
    }

    public File[] sort(File[] f)
    {
    for(int j = 1; j < f.length; j++)
    for(int i = 0; i < f.length - j; i++)
    {
    if(f[i].lastModified() > f[i+1].lastModified())
    {
    File t ;
    t = f[i];
    f[i] = f[i+1];
    f[i+1] = t;
    }
    }

    return f;
    }

    public static void main(String[] a) throws IOException
    {
    new FindDectory() .FindFiles("c:\\");
    }
    }