Java – Convert Milliseconds to Date

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MillisToDate {

	public static void main(String args[]) {

		//Converting milliseconds to Date using java.util.Date
		//current time in milliseconds
		long currentDateTime = System.currentTimeMillis();

		//creating Date from millisecond
		Date currentDate = new Date(currentDateTime);

		//printing value of Date
		System.out.println("current Date: " + currentDate);

		DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss");

		//formatted value of current Date
		System.out.println("Milliseconds to Date: " + df.format(currentDate));

		//Converting milliseconds to Date using Calendar
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(currentDateTime);
		System.out.println("Milliseconds to Date using Calendar:" + df.format(cal.getTime()));

		//copying one Date's value into another Date in Java
		Date now = new Date();
		Date copiedDate = new Date(now.getTime());

		System.out.println("original Date: " + df.format(now));
		System.out.println("copied Date: " + df.format(copiedDate));
	}

}

Output:

current Date: Wed Feb 29 01:58:46 VET 2012
Milliseconds to Date: 29:02:12:01:58:46
Milliseconds to Date using Calendar:29:02:12:01:58:46
original Date: 29:02:12:01:58:46
copied Date: 29:02:12:01:58:46

Java – Convert String to InputStream

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringToInputStreamExample {

	public static void main(String[] args) throws IOException {
		String str = "This is a String ~ GoGoGo";

		// convert String into InputStream
		InputStream is = new ByteArrayInputStream(str.getBytes());

		// read it with BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}

		br.close();
	}

}

Java – Convert InputStream to String

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToStringExample {

	public static void main(String[] args) throws IOException {
		//intilize an InputStream
		InputStream is = new ByteArrayInputStream("file content".getBytes());

		//read it with BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		StringBuilder sb = new StringBuilder();

		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}

		System.out.println(sb.toString());

		br.close();
	}

}

Page 1 of 212