Created
April 29, 2014 07:20
-
-
Save shsdev/11392809 to your computer and use it in GitHub Desktop.
Using jackson-dataformat-csv to create CSV file out of POJOs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.annotation.JsonPropertyOrder; | |
import com.fasterxml.jackson.databind.ObjectWriter; | |
import com.fasterxml.jackson.dataformat.csv.CsvMapper; | |
import com.fasterxml.jackson.dataformat.csv.CsvSchema; | |
import java.io.BufferedOutputStream; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.OutputStreamWriter; | |
import java.io.UnsupportedEncodingException; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Using jackson-dataformat-csv to create CSV file out of POJOs (bean class). | |
* Use with maven-dependency: | |
* <dependency> | |
* <groupId>com.fasterxml.jackson.dataformat</groupId> | |
* <artifactId>jackson-dataformat-csv</artifactId> | |
* <version>2.3.3</version> | |
* </dependency> | |
* https://github.com/FasterXML/jackson-dataformat-csv | |
*/ | |
public class CsvCreator { | |
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException { | |
// POJO (bean class) | |
@JsonPropertyOrder({"name", "age"}) | |
class User { | |
public String name; | |
public int age; | |
public User() { | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
} | |
// define objects | |
User user1 = new User(); | |
user1.name = "foo"; | |
user1.age = 32; | |
User user2 = new User(); | |
user2.name = "bar"; | |
user2.age = 27; | |
List<User> users = new ArrayList<User>(); | |
users.add(user1); | |
users.add(user2); | |
// create mapper and schema | |
CsvMapper mapper = new CsvMapper(); | |
CsvSchema schema = mapper.schemaFor(User.class); | |
schema = schema.withColumnSeparator('\t'); | |
// output writer | |
ObjectWriter myObjectWriter = mapper.writer(schema); | |
File tempFile = new File("users.csv"); | |
FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile); | |
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(tempFileOutputStream, 1024); | |
OutputStreamWriter writerOutputStream = new OutputStreamWriter(bufferedOutputStream, "UTF-8"); | |
myObjectWriter.writeValue(writerOutputStream, users); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks