运行java代码时出现arrayoutofbond错误

时间:2014-02-20 05:19:10

标签: java

  1. 我在给定代码下运行时遇到arrayoutofbond错误,
    有时候它按预期运行,有时会出错。 任何人都可以在我错的地方帮助我。

       import java.io.BufferedReader;
       import java.io.BufferedWriter;
       import java.io.File;
       import java.io.FileInputStream;
       import java.io.FileNotFoundException;
       import java.io.FileWriter;
       import java.io.IOException;
       import java.io.InputStreamReader;
       import java.text.SimpleDateFormat;
       import java.util.ArrayList;
       import java.util.Date;
    
       public class getFileContent{
    
        public void listFiles() throws IOException, InterruptedException{
    
            File directory = new File("C:\\ScriptLogFile\\"); 
            File[] myarray;  
            myarray=directory.listFiles();
            int i=0;
            ArrayList<String> arrayList = new ArrayList<String>();
            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");   
            Date curDate = new Date();   
            String strDate = sdf.format(curDate);   
            String fileName = strDate;
            File file = new File("C:\\ExcelReport_"+fileName+".csv");
            FileWriter fileWritter = new FileWriter(file, true);
            BufferedWriter bwr = new BufferedWriter(fileWritter);
            String filename = null; 
            try {
                for (int j = 0; j < myarray.length; j++)
                {
                    File path=myarray[j];
                    FileInputStream  fis = new FileInputStream (path);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    if(path.isFile()){
                        if(path.getName().endsWith(".csv")){
                            filename = path.getName();
                            String line;
                            bwr.write(filename+",");
                            while ((line = br.readLine()) != null) {
                                if(line.contains("-")){
                                    String[] part = line.split("-");
                                    arrayList.add(part[1]);
                                    bwr.write(arrayList.get(i)+",");
                                    i++;
                                }
                                else{
    
                                }
                            }
                            bwr.write("\r\n");
                        }
                    }
    
                }
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            bwr.close();
        }
    
        public static void main(String[] args) throws IOException, InterruptedException {
            getFileContent gfc = new getFileContent();
            gfc.listFiles();
        }
       }
    

1 个答案:

答案 0 :(得分:1)

我们需要一个堆栈跟踪来查看引发异常的位置。但是,您似乎在假设part[]的长度。记住数组是0索引的,第一个条目是索引0,即part[0]。即便如此,通常根本不需要很多条目:"xyz".split("-")是长度为1的数组,其唯一元素"xyz"位于索引0处。