我有两个CSV文件。 CSV1具有列Fname,Lname,weight,Occup。 CSV2具有列名称,重量,职业。 两者都有3个条目(行),并且都具有相同的Fname和Lname。
我希望用Java或Groovy映射它们,使得两个文件中的相同名称在控制台或新文件中输出为Fname; Lname; weight; Occupation。 ';'是使用分隔符。
感谢。
答案 0 :(得分:0)
伪代码快速而肮脏(而不是A +材质),因为你没有给我们任何东西......
您应该创建一个POJO来保存CSV1中的数据。将每个数据对象收集到一个列表中,并遍历列表以写入CSV2
/**
* POJO represents one entry in the CSV1 file
*/
public class Person
{
private String fName_;
private String lName_;
private String weight_;
private String occup_;
public Person(String fName, String lName String weight, String occup)
{
// Set each private member in this class with the value passed into this constructor
}
public String getFName()
{
return fName_;
}
// Getters for each private member here
}
然后实现逻辑就像......
public static void main(String[] args)
{
Path csv1 = Paths.get("C:/Users/haqpah/csv1.csv");
Path csv2 = Paths.get("C:/Users/haqpah/csv2.csv");
String csvFileAsString = new String(Files.readAllBytes(csv1));
int endIndex = csvFileAsString.indexOf(",");
String fName = csvFileAsString.substring(0, endIndex);
csvFileAsString = csvFileAsString.substring(endIndex + 1); // removes the first value and comma from the String
endIndex = csvFileAsString.indexOf(",");
String lName = csvFileAsString.substring(0, endIndex);
csvFileAsString = csvFileAsString.substring(endIndex + 1); // removes the next value and comma from the String
// Do the same for weight
// Do the same for occupation
Person person = new Person(fName, lName, weight, occup);
// Figure out how to collect all the Person objects you make
List<Person> personList = ...;
for(Person person : personList)
{
StringBuilder sb = new StringBuidler();
sb.append(person.getFName() + ", " person.getLName().....);
Files.write(csv2, sb.toString().getBytes()); // Figure out how to append instead of create new
}
}