簡體   English   中英

運行Java代碼時出現arrayoutofbond錯誤

[英]Getting arrayoutofbond error while running java code

  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(); } } 

我們需要一個堆棧跟蹤來查看引發異常的位置。 但是,您似乎正在對part[]的長度進行假設。 請記住,數組是0索引的,第一個條目將在索引0處,即part[0] 即使到那時,通常實際上根本也不需要太多條目: "xyz".split("-")是長度為1的數組,其唯一元素"xyz"索引為0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM