ArrayList返回null的方法

时间:2013-11-07 11:25:50

标签: java jsp servlets arraylist

我希望此方法返回包含目录中所有文件名的字符串列表。我声明的List从方法返回null。有谁知道为什么?代码段张贴在下面。

   public static String docxList() {
        String path1 = "E:\\";
        String files = null;
        String display = null;
        String dpmt=null;

    //String variables declaration,
    try{
        Class.forName("oracle.jdbc.driver.OracleDriver");   
        java.sql.Connection 
        con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","pass");
        //Database connection Code
        PreparedStatement ps=con.prepareStatement("select * from EMP_DB where EMP_ID='EI-12'");
        ResultSet rs=ps.executeQuery();
        rs.next();
        dpmt=rs.getString("DEPARTMENT");

        path1 =path1+dpmt; //New path generation of specific directory according to user department

        File folder = new File(path1);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++)
        {
            if (listOfFiles[i].isFile())
            {
                files = listOfFiles[i].getName();
                String filename=files;
                if(filename.indexOf(".")>0)
                {
                    filename=files.substring(0,files.lastIndexOf("."));
                }

                display=('<'+"A HREF"+'='+"\""+"PDFs/"+dpmt+"/"+files+"\""+" "+"target"+'='+"\""+"targetiframe"+"\""+'>'+'<'+"font"+" size"+'='+"\"4\""+" color"+'='+"\"white\""+'>'+filename+"</font>"+"<"+"/A"+'>');
                //Hyper-linked list of files. 
                ArrayList<String> al=new ArrayList<String>();
                al.add(display);
                //Adding all file names in a directory to a Arraylist.      
            }
        }
    }
    catch(Exception ex) 
    {
        System.out.print("Exception: "+ex+" in Dpmt Method.");  
        //Exception Display if any.
    }                                   

    return al; //ArrayList doesn't generate list of files in the drectory.
}

2 个答案:

答案 0 :(得分:3)

您在返回语句无法看到的范围内重新插入数组列表。将以下语句放在 for 循环之前。

ArrayList<String> al = new ArrayList<String>();

所以,它看起来像这样 -

File[] listOfFiles = folder.listFiles();
ArrayList<String> al = new ArrayList<String>();

for (int i = 0; i < listOfFiles.length; i++)

..你的其余代码..

修改

您还应该修改方法签名以返回列表,而不是String。

public static ArrayList<String> docxList()

答案 1 :(得分:0)

您需要在List<String>块之外声明try/catch,以使其位于return语句的范围内。此外,当您尝试返回String时,您的返回类型目前为List<String>,因此如果您确实想要返回List,则还需要更改。您的方法应如下所示:

public static List<String> docxList() {
    String path1 = "E:\\";
    String files = null;
    String display = null;
    String dpmt=null;
    List<String> al = new ArrayList<String>();

    try { 
        // code... 
    }
    catch(Exception ex) {
        // handle exception..
    }                                   

    return al; 
}