将java对象转换为管道分隔的字符串

时间:2015-12-09 04:25:19

标签: java string serialization

假设有课程:

public class Employee 
{
   private String name;
   private String age;
   private String birthdate;
   private String location;
}

我们有一个值为name = John,age = 25,birthdate = 9月10日,location = houston的对象。是否有一种简单的方法或有效的方法将该对象转换为管道分隔的字符串,如下所示?

John|25|September 10|houston

我只能想到一个解决方案 - 只需将对象成员的值附加到字符串中即可。我想知道是否有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:3)

使用String.format

System.out.println (String.format ("%s|%s|%s|%S", name, age, birthdate, location));

将此卡入您的覆盖toString方法