[英]Read and parse CSV file in java
我有兩個csv文件。
CSV File1 = csvFrom,//它有兩列,column1 =電子郵件(僅5封電子郵件),column2 =密碼
CSV File2 = csvSendTo //只有一列= Email。 (成千上萬的電子郵件)。
我正在嘗試讀取csvFrom文件,我想要第一個文件的第一個電子郵件ID及其密碼。 然后從第二個csvSendTo文件發送20封電子郵件。 想要從第一個電子郵件ID和密碼發送電子郵件到這20封電子郵件。 我可以使用一個電子郵件ID手動發送電子郵件。 但是,當我嘗試從csv文件讀取它時,它給了我NullPointerException。 下面是我的代碼:我只是將零件粘貼到這里,這給了我一個錯誤。 有人可以在這里引導我嗎? 這個for循環在這里是錯誤的,但是我有點困惑,所以不能用精確的循環代替。
BufferedReader br1=null;
BufferedReader br2=null;
String line1="",line2="";
String csvSplitBy=",";
String strMailFrom="",strPassword="";
int countCSVFrom=0,countCSVSendTo=0;
System.out.println("strCSVFrom=" + strCSVFrom + ", strcsvSendTo=" + strCSVSendTo);
try{
br1=new BufferedReader(new FileReader(strCSVFrom));
br2=new BufferedReader(new FileReader(strCSVSendTo));
String[] strarrFromEmail;
while((line1=br1.readLine())!=null){
countCSVFrom+=1;
strarrFromEmail=line1.split(csvSplitBy);
// for(int i=countCSVFrom-1;i<=countCSVFrom;i++){
// strMailFrom=strarrFromEmail[i];
// strPassword=strarrFromEmail[i+1]; //While here its ArrayIndexOutOfBounds Exception
// }
//what is the correct thing to write it over here instead of for loop?
}
System.out.println("countcsvfrom="+countCSVFrom + ", line1=" + line1.toString()); //Giving me an error of NullPointerException over here.
System.out.println("strFrom="+strMailFrom + ", strPassword="+strPassword);
while((line2=br2.readLine())!=null){
countCSVSendTo+=1;
}
System.out.println("countcsvsendto="+countCSVSendTo);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
第二個System.out.println
在第一個while
循環的右括號之后,給出了NPE。 它使用line1
,該while
循環保證的終止條件在那時將為null
。
您可以這樣寫:
//your code here and try catch block below
try {
List<String[]> csvLines = new ArrayList<String[]>();
Files.lines(Paths.get(strCSVFrom)).map(e -> e.split(csvSplitBy)).forEach(csvLines.add(e));
} catch (Exception) {
//exception handling
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.