Write Binary Data : 

We can use Node API classes ValueFactory and Value to store binary data into JCR. ValueFactory can be used to create Binary object from InputStream and Value object from binary object.


String html = "<html><head></head><body>
<h1>Welcome</h1>
</body></html>";
InputStream stream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8.name()));

ValueFactory factory = session.getValueFactory();
Binary binary = factory.createBinary(stream);
Value value = factory.createValue(binary);
Node node = // create node object;
node.setProperty("jcr:data", value);
node.getSession().save();

Read Binary Data:

ValueMap properties = getProperties();
properties.get("jcr:data", InputStream.class);
html2 = IOUtils.toString(properties.get("jcr:data", InputStream.class), "UTF-8");

Example :

package com.demoportal.aem.models.component;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import org.apache.commons.io.IOUtils;
import org.apache.sling.api.resource.ValueMap;
import com.adobe.cq.sightly.WCMUsePojo;
public class BinaryJcrData extends WCMUsePojo{
  String html2;
@Override public void activate() throws Exception {
  /* Write binary data into node */
   String html = "<html><head></head><body>
<h1>Welcome</h1>
</body></html>";
   InputStream stream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8.name()));
   ValueFactory factory = getResourceResolver().adaptTo(Session.class).getValueFactory();
   Binary binary = factory.createBinary(stream);
   Value value = factory.createValue(binary);
   Node node = getResource().adaptTo(Node.class);
   node.setProperty("jcr:data", value);
   node.getSession().save();

   /* Read Binary data from JCR node */
   ValueMap properties = getProperties();
   properties.get("jcr:data", InputStream.class);
   html2 = IOUtils.toString(properties.get("jcr:data", InputStream.class), "UTF-8");
}
public String getHtml2() {
  return html2;
}
}