code: public static void saveCertificate(X509Certificate cert, File targetFile) {
          File folder = targetFile.getAbsoluteFile().getParentFile();
          if (!folder.exists()) {
              folder.mkdirs();
          }
          File tmpFile = new File(folder, Long.toHexString(System.currentTimeMillis()) + ".tmp");
          try {
              boolean asPem = targetFile.getName().toLowerCase().endsWith(".pem");
              if (asPem) {
                  // PEM encoded X509
                  PEMWriter pemWriter = null;
                  try {
                      pemWriter = new PEMWriter(new FileWriter(tmpFile));
                      pemWriter.writeObject(cert);
                      pemWriter.flush();
                  } finally {
                      if (pemWriter != null) {
                          pemWriter.close();
                      }
                  }
              } else {
                  // DER encoded X509
                  FileOutputStream fos = null;
                  try {
                      fos = new FileOutputStream(tmpFile);
                      fos.write(cert.getEncoded());
                      fos.flush();
                  } finally {
                      if (fos != null) {
                          fos.close();
                      }
                  }
              }
  
              // rename tmp file to target
              if (targetFile.exists()) {
                  targetFile.delete();
              }
              tmpFile.renameTo(targetFile);
          } catch (Exception e) {
              if (tmpFile.exists()) {
                  tmpFile.delete();
              }
              throw new RuntimeException("Failed to save certificate " + cert.getSubjectX500Principal().getName(), e);
          }
      }
docs: Saves the certificate to the file system.  If the destination filename
  ends with the pem extension, the certificate is written in the PEM format,
  otherwise the certificate is written in the DER format.
  
  @param cert
  @param targetFile