[英]How to Read large size csv file and split each line to string array in java
我有GB大小的csv文件,我能夠讀取,但是將其拆分為數組然后打印時會導致ArrayIndexOutOfBoundsException這是我的程序
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("file.csv");
sc = new Scanner(inputStream, "UTF-8");
int j=0;
while (sc.hasNextLine()) {
String[] data=new String[4];
String line=sc.nextLine();
data=line.split(",");
System.out.println(data[0]+" "+data[1]+" "+data[2]+" "+data[3]);
}
if (sc.ioException() != null) {
throw sc.ioException();
}
}
catch (IOException ex) {
Logger.getLogger(TestPrintingAllLine.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
在執行了536行之后,它導致->
線程“主”中的異常java.lang.ArrayIndexOutOfBoundsException:3在enterdatatosql.TestPrintingAllLine.main(TestPrintingAllLine.java:45)Java結果:1。
第45行是-> System.out.println(data [0] +“” + data [1] +“” + data [2] +“” + data [3]);
我會將其發布為評論,但可能會變得凌亂。
您應該檢查每個拆分是否有“ 4個部分”,因為某些行可能只有3/2 / etc。
System.out.println(data[0]+" "+data[1]+" "+data[2]+" "+data[3]);
在此行之前,首先檢查data
有四個部分。
編輯
我認為您的問題出在536行上,您只有兩個逗號而不是三個。 這意味着您的數據數組將如下所示:
| ---- | ---- | ---- | 0 1 2 <-索引
您通常會在哪里:
| ---- | ---- | ---- | ---- | 0 1 2 3 <-索引
由於您的打印行將要打印索引3
,因此您將得到索引超出范圍錯誤,因為此行上沒有索引為3的“部分”。
在打印數據[0],數據[1],數據[2]和數據[3]之前,請檢查其是否為空..在少數幾行數據[1]或數據[2]或數據[3中可能是這種情況]將為空,並且正在生成此錯誤
試試這個代碼:
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
public class ReadValues {
public static void main(String[] args) throws IOException {
FileInputStream stream = new FileInputStream("D:\\jointIndustry\\Test\\src\\input.csv");
String data = IOUtils.toString(stream);
String data1[] = data.split(",");
for(String str : data1){
System.out.println(str);
}
}
}
您需要從maven / apache網站下載commons-io-1.3.2.jar並將其設置為classapth
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.