fork download
  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. class Attachement {
  6. private final File file;
  7. public Attachement(String path) {
  8. file = new File(path);
  9. }
  10. public String toJsonString() {
  11. return " { \"path\": \"" + file.getAbsolutePath() + "\" }";
  12. }
  13. }
  14.  
  15. class AttachementHolder {
  16. private final List<Attachement> attachements = new ArrayList<Attachement>();
  17. public void addAttachement(Attachement attachement) {
  18. attachements.add(attachement);
  19. }
  20. public String toJSON() {
  21. StringBuilder sb = new StringBuilder("{\n\"files\": [\n");
  22. boolean addSeparator = false;
  23. for (Attachement attachement : attachements) {
  24. if (addSeparator) {
  25. sb.append(",\n");
  26. } else {
  27. addSeparator = true;
  28. }
  29. sb.append(attachement.toJsonString());
  30. }
  31. sb.append("\n ]\n}");
  32. return sb.toString();
  33. }
  34. }
  35.  
  36. public class Main {
  37.  
  38. public static void main(String[] args) {
  39. AttachementHolder holder = new AttachementHolder();
  40. holder.addAttachement(new Attachement("/home/file1"));
  41. holder.addAttachement(new Attachement("/home/file2"));
  42. holder.addAttachement(new Attachement("/home/file3"));
  43. System.out.println(holder.toJSON());
  44. }
  45. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
{
"files": [
  { "path": "/home/file1" },
  { "path": "/home/file2" },
  { "path": "/home/file3" }
 ]
}