我正在将Outlook SCV
文件解析为ArrayList
。
然后,我希望获得String
列表的Array
值。
以下是代码:
if(arr != null){
try{
for (int i = 1; i < arr.size(); i++) {
oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
StringBuilder strBuild = new StringBuilder();
strBuild.append(String.valueOf(oneRow.get(j).toString()));
无论我尝试了什么,我都无法获得String
价值。
我得到的是:[Ljava.lang.string @ ....
以下是使ArrayList
获取CSV
文件并构建ArrayList
的{{1}}的类:
public class ReadingCSV {
InputStream inputStream;
public ReadingCSV(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
ArrayList resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
答案 0 :(得分:2)
注意: - 使用
编译和运行此代码jdk V1.8
试试这个是一个有效的代码。你可以根据自己的需要进行操作。
public List<String> read(){
ArrayList<String> resultList = new ArrayList(); //A Type-Safety (String) ArrayList
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(","); //row is String Array Object
for(String eachWord : row) //Iterate each String from the array
resultList.add(eachWord); // add String to the Type-Safe ArrayList.
}
}catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
使用此
更新您的另一个代码if(arr != null){
for (int i = 1; i < arr.size(); i++) {
ArrayList<String> oneRow = new ArrayList();
oneRow.add(arr.get(i));
for (int j = 0; j < oneRow.size(); j++) {
strBuild.append(oneRow.get(j));
}
}
System.out.println(strBuild.toString());
}
本守则完美无缺。你可以自己尝试一下。如有任何问题,您可以发表评论。
答案 1 :(得分:0)