Popular Java Examples
In this serious of posts, I will list some popular java programs. They are related to Singleton Pattern, File read and write, Java Date conversion, Java collections usage, Java HashMap usage.
1. Java Singleton example
Please refer to this post: five ways to implement Java Singleton
2. Java read file using BufferedReader
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileTest { public static void main(String[] args) throws IOException { BufferedReader br = null; try { String curLine; br = new BufferedReader(new FileReader("/tmp/user/xxx.txt")); while ((curLine = br.readLine()) != null) { System.out.println(curLine); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null){ br.close(); } } } } |
3. Java Append a String to a file
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class AppendFileTest{ public static void main(String[] args) throws IOException { BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter("/tmp/for_append.txt", true)); out.write("append a string "); } catch (IOException e) { // error processing code } finally { if (out != null) { out.close(); } } } } |
4. Convert String to Date in Java
|
1 |
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String); |
or
|
1 2 |
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" ); Date date = format.parse( myString ); |
5. Convert Java util.Date to sql.Date
This snippet shows how to convert a java util Date into a sql Date for use in databases.
|
1 2 |
java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); |
6. Java Convert Byte to String
In order to convert Byte array into String format correctly, we must explicitly create a String object and assign the Byte array to it.
|
1 |
String s = new String(bytes); |
7. Java List for Loop
See the post for how to loop a Java List.
8. Java HashMap for loop
See this post for how to loop a java Hashmap.
9. Use Java HashMap to Count Word frequency
Please refer to this post for how to count word frequency using HashMap.
To be continued…











