gpt4 book ai didi

java - 如何从 Java arraylist 中删除空的 csv 记录?

转载 作者:行者123 更新时间:2023-11-30 06:12:00 24 4
gpt4 key购买 nike

我有一个要求,我需要获取一些值,然后将所有这些值写入 csv 文件。为此,我将值添加到 Java Arraylist 并写入 csv 文件。但是当我这样做时,它会将记录写入 CSV,但记录之间有空行。不确定为什么会出现此问题。

1,abc,fname,lname,email,log


1,abc1,fname1,lname1,email1,log1
1,abc2,fname2,lname2,email2,log2


1,abc3,fname3,lname3,email3,log3
1,abc4,fname4,lname4,email4,log4

这是我的代码。请告诉我这段代码有什么问题:

public StringBuilder fetchUsers() {
ArrayList<String> users = null;
StringBuilder sb1 = new StringBuilder();
try {
client = getMyClient();
if (client != null) {
UserList usersList = getUsers();
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
System.out.println("usersList.totalCount ----->"
+ usersList.totalCount);

for (KalturaUser user : usersList.objects) {
users = new ArrayList<String>();
if (user != null) {
String action = null;
String userFullName = null;
String modifiedName = null;
String firstName = user.firstName;
if (user.id != null) {
String cnum = getUserUniqueId(user.id);
String userRole = getUserRole(user.id);
if (cnum != null || userRole != null) {
action = validateCnum(cnum, userRole);
if (!action.equals("3")) {
users.add(action);
users.add(cnum);
if (firstName != null
&& firstName.contains("@")) {
user.email = firstName;
userFullName = getUserNames(user.id);
firstName = userFullName;
}
users.add(firstName);
users.add(user.lastName);
users.add(user.email);
users.add(userRole);
}
}
}
}
allUsers.add(users);
}
}
}
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writeToCSV();
return sb1;
}


private void writeToCSV() {
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System
.getProperty("line.separator"));
try {
fileWriter = new FileWriter("C:/users.csv");
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(USER_COLUMNS);
for (List<String> rowData : allUsers) {
csvFilePrinter.printRecord(rowData);
}
} catch (Exception e) {
logger.error(e.getStackTrace());
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
logger.error("Error while flushing/closing fileWriter/csvPrinter!");
}
}
}

最佳答案

这个:

 allUsers.add(users);

应该在 if (user != null) 和所有子 ifs 中

像这样:

if (user != null) {
...
if (user.id != null) {

...
if (cnum != null || userRole != null) {
....
if (!action.equals("3")) {
users = new ArrayList<String>();
....
allUsers.add(users);
}
}
}
}

一般来说,只有当你有东西要添加时,你才应该创建数组并将它添加到 allUsers

关于java - 如何从 Java arraylist 中删除空的 csv 记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33392046/

24 4 0