Dateien und Verzeichnisse

Java is auch eine Insel: Dateien und Verzeichnisse.

JSON

Create a class to hold the values, e.g. for a person, add annotations to its constructor

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private final String name;
    private final Integer age;

    @JsonCreator
    public Person(@JsonProperty("name") final String name, @JsonProperty("age") final Integer age) {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }
}

Turn an object into a JSON String, and a JSON String into an object

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonPlay {

    public static void object2JsonString() throws JsonProcessingException {
        // http://www.studytrails.com/java/json/jackson-create-json.jsp

        final ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        mapper.setSerializationInclusion(Include.NON_EMPTY);

        final Person john = new Person("John Jones", 42);
        final String jsonString = mapper.writeValueAsString(john);
        // { "name" : "John Jones", "age" : 42 }
        System.out.println(jsonString);

    }

    public static void jsonString2Object() throws JsonParseException, IOException {
        final String json = "{ \"name\" : \"John Jones\", \"age\" : 42 }";
        final ObjectMapper mapper = new ObjectMapper();
        final Person john = mapper.readValue(json, Person.class);
        System.out.println(john);
    }

You might want to control the serialization or de-serialization of a field or even of a whole class

@JsonSerialize(using = Foo.CustomSerializer.class)
@JsonDeserialize(using = Foo.CustomDeSerializer.class)
public class Foo {     

  ...

  public Foo() {
  }

  static class CustomDeSerializer extends JsonDeserializer<Foo> {
   ObjectMapper mapper=new ObjectMapper();

   @Override
   public Foo deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
     Foo result=new Foo();     
     JsonNode node = parser.getCodec().readTree(parser);
     Iterator<Entry<String, JsonNode>> iter = node.fields();
     while(iter.hasNext()) {
       Entry<String, JsonNode> node = iter.next();
        result.set...
     }
     return result;
   }
  }

  static class CustomSerializer extends JsonSerializer<Foo> {
    @Override
    public void serialize(Foo value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
      jgen.writeStartObject();
      ...
      jgen.writeBooleanField("...", ...);
      ...
      jgen.writeEndObject();
    }
  }
}

Watch out if you try to create json out of an object that has a Map with a non trivial key typ. That is a mess. Maybe try to have String or enum instead

https://www.baeldung.com/jackson-map

Java XML

JavaXML

CSV Dateien auslesen

OpenCSV

import au.com.bytecode.opencsv.CSVReader;
...

  CSVReader reader = new CSVReader("Foo.csv", ',');
  List<String[]> myEntries = reader.readAll();

Excel Dateien schreiben und lesen

Apache POI

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

...

XSSFWorkbook workbook=new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("My Excel Sheet");
XSSFRow  row0  = sheet.createRow(0);
{
 XSSFCell cell0 = row0.createCell(0);
 XSSFCell cell1 = row0.createCell(1);
 cell0.setCellValue(Number);
 cell1.setCellValue(Date);
}

XSSFRow  row1  = sheet.createRow(1);
{
 XSSFCell cell3 = row1.createCell(1);
 cell3.setCellValue(42);

 XSSFCell cell4 = row1.createCell(2);
 cell4.setCellValue(new Date());

 XSSFCellStyle cellStyle = workbook.createCellStyle();
 cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd"));                  
 cell4.setCellStyle(cellStyle);
}

sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);

File output=new File(“excelfile.xlsx);
FileOutputStream out = new FileOutputStream(output);
workbook.write(out);

out.close();

Access file located in the classpath

URL url = this.getClass().getClassLoader().getResource(pFilename);
if(url!=null)
{
    return url.getPath();
}

This would look for the file directly in src/main/resources. However, you should create subfolders there matching the class package (e.g. if the package would be de.tgunkel.java create de/tgunkel/java/) and put the file there. In order to access it there use (without getClassLoader)

URL url = this.getClass().getResource(pFilename);

Add / in front of the the filename would again access files in the root folder.

You should avoid to get the URL first and then try to read it but use getResourceAsStream to directly get a stream, no matter how wired the URL might be (e.g. a file inside a JAR)

Example

private String testFileContent(final String filename) throws IOException {
        try (InputStream in = getClass().getResourceAsStream(filename)) {
                final String myString = IOUtils.toString(in, "UTF-8");
                return myString;
        }
}