Code snipplet


Some code snipplet useful everyday:

Read a file line by line:

InputStream in=this.getClass().getClassLoader().getResourceAsStream("aaa.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while(br.readLine()==null) { .... }

Integer to hexadecimal string:

String hex=Integer.toHexString(number);

Pretty Print XML Document:

org.w3c.dom.Document document=...;
try {
  javax.xml.transform.TransformerFactory tfactory = 
                          javax.xml.transform.TransformerFactory.newInstance();
  javax.xml.transform.Transformer xform = tfactory.newTransformer();
  xform.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
  xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
  java.io.StringWriter writer = new java.io.StringWriter();
  javax.xml.transform.Result result = 
                               new javax.xml.transform.stream.StreamResult(writer);
  xform.transform(new javax.xml.transform.dom.DOMSource(document), result);
  System.out.println(writer.toString());
} catch (Exception e) {
  e.printStackTrace();
}

Marshall JAXB to a file:

JAXBContext jaxbC;
try {
      jaxbC = JAXBContext.newInstance(jaxbClass.class);
      Marshaller marshaller = jaxbC.createMarshaller();
      marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
      marshaller.marshal(jaxbObject, new File("c:/aaa.txt"));
} catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}

Print InputStream:

InputStream input=...;
byte[] buffer = new byte[1024];
int len = input.read(buffer);
while (len != -1) {
    System.out.write(buffer, 0, len);
    len = input.read(buffer);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: