How to list all character sets supported by the java jvm?

Question:
How to list all character sets supported by a JVM?

Code:
import java.util.Map;
import java.nio.charset.Charset;
import java.util.Set;
 
public class AvailableCharsets {
  public static void main(String[] args) {
    Map<String, Charset> map = Charset.availableCharsets();
    Set<String> keys = map.keySet();
    for (String charsetName : keys) {
      System.out.println(charsetName);
    }
  }
}

Output:
$ java AvailableCharsets
Big5
Big5-HKSCS
EUC-JP
EUC-KR
GB18030
GB2312
GBK
IBM-Thai
IBM00858
IBM01140
IBM01141
IBM01142
IBM01143
IBM01144
IBM01145
IBM01146
IBM01147
IBM01148
IBM01149
IBM037
IBM1026
IBM1047
IBM273
IBM277
IBM278
IBM280
IBM284
IBM285
IBM290
IBM297
IBM420
IBM424
IBM437
IBM500
IBM775
IBM850
IBM852
IBM855
IBM857
IBM860
IBM861
IBM862
IBM863
IBM864
IBM865
IBM866
IBM868
IBM869
IBM870
IBM871
IBM918
ISO-2022-CN
ISO-2022-JP
ISO-2022-JP-2
ISO-2022-KR
ISO-8859-1
ISO-8859-13
ISO-8859-15
ISO-8859-2
ISO-8859-3
ISO-8859-4
ISO-8859-5
ISO-8859-6
ISO-8859-7
ISO-8859-8
ISO-8859-9
JIS_X0201
JIS_X0212-1990
KOI8-R
KOI8-U
Shift_JIS
TIS-620
US-ASCII
UTF-16
UTF-16BE
UTF-16LE
UTF-32
UTF-32BE
UTF-32LE
UTF-8
windows-1250
windows-1251
windows-1252
windows-1253
windows-1254
windows-1255
windows-1256
windows-1257
windows-1258
windows-31j
x-Big5-HKSCS-2001
x-Big5-Solaris
x-COMPOUND_TEXT
x-euc-jp-linux
x-EUC-TW
x-eucJP-Open
x-IBM1006
x-IBM1025
x-IBM1046
x-IBM1097
x-IBM1098
x-IBM1112
x-IBM1122
x-IBM1123
x-IBM1124
x-IBM1364
x-IBM1381
x-IBM1383
x-IBM300
x-IBM33722
x-IBM737
x-IBM833
x-IBM834
x-IBM856
x-IBM874
x-IBM875
x-IBM921
x-IBM922
x-IBM930
x-IBM933
x-IBM935
x-IBM937
x-IBM939
x-IBM942
x-IBM942C
x-IBM943
x-IBM943C
x-IBM948
x-IBM949
x-IBM949C
x-IBM950
x-IBM964
x-IBM970
x-ISCII91
x-ISO-2022-CN-CNS
x-ISO-2022-CN-GB
x-iso-8859-11
x-JIS0208
x-JISAutoDetect
x-Johab
x-MacArabic
x-MacCentralEurope
x-MacCroatian
x-MacCyrillic
x-MacDingbat
x-MacGreek
x-MacHebrew
x-MacIceland
x-MacRoman
x-MacRomania
x-MacSymbol
x-MacThai
x-MacTurkish
x-MacUkraine
x-MS932_0213
x-MS950-HKSCS
x-MS950-HKSCS-XP
x-mswin-936
x-PCK
x-SJIS_0213
x-UTF-16LE-BOM
X-UTF-32BE-BOM
X-UTF-32LE-BOM
x-windows-50220
x-windows-50221
x-windows-874
x-windows-949
x-windows-950
x-windows-iso2022jp

How to assign file content to a String in Java

Question:
How to copy the content of a file to a String using Java?

Code:
import java.io.DataInputStream;
import java.io.FileInputStream;
 
public class FileToString {
 
   public static void main(String args[]) {
 
      try {
 
         FileInputStream fis = new FileInputStream("/tmp/myfile.txt");
         DataInputStream dis = new DataInputStream(fis);
 
         byte[] data = new byte[dis.available()];
         dis.readFully(data);
         dis.close();
 
         String content = new String(data, 0, data.length);
 
         System.out.println(content);
 
      } catch (Exception ex) {
         System.out.println(ex);
      }
 
   }
}

Output:
$ java FileToString
This is an example on how to copy the contents of a file to a String using Java.



$ cat myfile.txt
This is an example on how to copy the contents of a file to a String using Java.

How to compress files in ZIP format in java?

Question:
How to compress files in ZIP format in java?

Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class CompressFile {
 
   public static void main(String[] args) {
 
      byte[] buffer = new byte[1024];
 
      try {
 
         FileOutputStream fos = new FileOutputStream("/tmp/myfile.zip");
         ZipOutputStream zos = new ZipOutputStream(fos);
         ZipEntry ze = new ZipEntry("myfile.txt");
         zos.putNextEntry(ze);
         FileInputStream in = new FileInputStream("/tmp/myfile.txt");
 
         int len;
         while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
         }
 
         in.close();
         zos.closeEntry();
 
         zos.close();
 
         System.out.println("Finished");
 
      } catch (IOException ex) {
         System.out.println(ex);
      }
   }
}

Output:
$ java CompressFile
Finished

$ ls -l /tmp/myfile.*
-rw-rw-r-- 1 dennis dennis 6880 Feb 27 06:37 /tmp/myfile.txt
-rw-rw-r-- 1 dennis dennis  178 Feb 27 06:39 /tmp/myfile.zip

How to get the total number of lines of a file in Java?

Question:
How to get the total number of lines of a file in Java?

Code:
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
 
public class CountLines {
 
  public static void main(String[] args) {
 
    try{
 
      FileReader fr = new FileReader("./CountLines.java");
      LineNumberReader lnr = new LineNumberReader(fr);
 
      int count = 0;
 
      while (lnr.readLine() != null){
        count++;
      }
      System.out.println("Total number of lines : " + count);
      lnr.close();
 
    } catch(IOException e) {
      System.out.println(e);
    }
 
  }
}

Output:
$ java CountLines
Total number of lines : 27

$ wc -l CountLines.java 
27 CountLines.java

How to decompress file from GZIP file using java?

Question:
How to decompress file from GZIP file using java?

Code:
import java.io.*;
import java.util.zip.GZIPInputStream;
 
public class GUnZipFile {
  public static void main( String[] args ) {
 
    String input = "/tmp/file.txt.gz";
    String output = "/tmp/file.txt";
 
    byte[] buffer = new byte[1024];
 
    try {
 
      FileInputStream fis = new FileInputStream(input);
      GZIPInputStream gzis = new GZIPInputStream(fis);
 
      FileOutputStream fos = new FileOutputStream(output);
 
      int len;
      while ((len = gzis.read(buffer)) > 0) {
         fos.write(buffer, 0, len);
      }
 
      gzis.close();
      fos.close();
      System.out.println("Done");
 
    } catch(Exception ex) {
      System.out.println(ex);
    }
  }
}

Output:
$ java GUnZipFile
Done

$ ls -l /tmp/file.txt.gz 
-rw-rw-r-- 1 dennis dennis 56 Feb 26 16:44 /tmp/file.txt.gz

$ ls -l /tmp/file.txt
-rw-rw-r-- 1 dennis dennis 4880 Feb 26 16:52 /tmp/file.txt

How to compress a file in GZIP format using java?

Question:
How to compress a file in GZIP format?

Code:
import java.io.*;
import java.util.zip.GZIPOutputStream;
 
public class GZipFile {
  public static void main( String[] args ) {
 
    String input = "/tmp/file.txt";
    String output = "/tmp/file.txt.gz";
 
    byte[] buffer = new byte[1024];
 
    try {
 
      FileInputStream in = new FileInputStream(input);
 
      FileOutputStream fos = new FileOutputStream(output);
      GZIPOutputStream gzos = new GZIPOutputStream(fos);
 
      int len;
      while ((len = in.read(buffer)) > 0) {
        gzos.write(buffer, 0, len);
      }
      in.close();
      gzos.finish();
      gzos.close();
      System.out.println("Done");
 
    } catch(Exception ex) {
      System.out.println(ex);
    }
  }
}

Output:
$ java GZipFile
Done

$ ls -l /tmp/file.txt
-rw-rw-r-- 1 dennis dennis 4880 Feb 26 16:42 /tmp/file.txt

$ ls -l /tmp/file.txt.gz
-rw-rw-r-- 1 dennis dennis 56 Feb 26 16:44 /tmp/file.txt.gz

How to convert InputStream to String in Java

Question:
How to convert InputStream to String in Java?

Code:
import java.io.*;
 
public class InputStreamToString {
 
   public static void main(String[] args) throws IOException {
 
      String str = "Do you like green eggs and ham. I do not like them, Sam I am.";
      InputStream is = new ByteArrayInputStream(str.getBytes());
      String result = getStringFromInputStream(is);
      System.out.println(result);
   }
 
   private static String getStringFromInputStream(InputStream is) {
 
      BufferedReader br = null;
      StringBuilder sb = new StringBuilder();
 
      String line;
      try {
         br = new BufferedReader(new InputStreamReader(is));
         while ((line = br.readLine()) != null) {
            sb.append(line);
         }
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
         if (br != null) {
            try {
               br.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return sb.toString();
   }
}

Output:
$ java InputStreamToString
Do you like green eggs and ham. I do not like them, Sam I am.

How to convert String to InputStream in Java?

Question:
How to convert String to InputStream in Java?

Code:
import java.io.*;
 
public class StringToInputStream {
   public static void main(String[] args) throws IOException {
 
      String str = "Do you like green eggs and ham? I do not like them, Sam I am.";
 
      // Convert String into InputStream
      InputStream is = new ByteArrayInputStream(str.getBytes());
 
      // Read it with BufferedReader
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
 
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
 
      br.close();
   }
}

Output:
$ java StringToInputStream
Do you like green eggs and ham? I do not like them, Sam I am.

How to check if a file is hidden in Java

Question:
How to check if a file is hidden in Java?

Answer:
Use the method isHidden() found in the class File.

Code:
import java.io.File;
import java.io.IOException;
 
public class HiddenFile {
 
   public static void main(String[] args) throws IOException { 
 
      File file = new File("/tmp/.hidden.txt");
 
      if(file.isHidden()) {
         System.out.println("File is hidden");
      } else {
         System.out.println("File is not hidden");
      }
   }
}

Output:
$ java HiddenFile
File is hidden

$ ls -l /tmp/.hidden.txt 
-rw-rw-r-- 1 dennis dennis 22 Feb 26 12:52 /tmp/.hidden.txt

How to change the file last modified date in Java?

Question:
How to change the file last modified date in Java?

Answer:
Use File.setLastModified()

Code:
import java.io.*;
import java.util.*;
import java.text.*;
 
public class ChangeModificationTime {
   public static void main(String[] args) {
      File file = new File("ChangeModificationTime.java");
 
      Date date = new Date(file.lastModified());
      System.out.println(date);
 
      try {
         String str = "01/31/1998";
         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
         Date newDate = sdf.parse(str);
         file.setLastModified(newDate.getTime());
      } catch(ParseException e) {
         System.out.println("ParseException");
      }
 
      date = new Date(file.lastModified());
      System.out.println(date);
 
   }
}

Output:
$ ls -l ChangeModificationTime.java 
-rw-rw-r-- 1 dennis dennis 664 Feb 26 12:44 ChangeModificationTime.java

$ java ChangeModificationTime
Thu Feb 26 12:44:31 EST 2015
Sat Jan 31 00:00:00 EST 1998

$ ls -l ChangeModificationTime.java 
-rw-rw-r-- 1 dennis dennis 664 Jan 31  1998 ChangeModificationTime.java

How to check if date is valid in Java

Question:
How to check if date is valid in java?

Answer:
Use SimpleDateFormat class to check if a provided date is valid.

Code:
import java.util.*;
import java.text.*;
 
public class TestDate {
   public static void main(String[] args) {
 
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
      sdf.setLenient(false);
 
      // Jan 28, 2015
      String str1 = "01/28/15";
 
      // invalid date
      String str2 = "124/12/12";
 
      try {
         Date date = sdf.parse(str1);
         System.out.println(str1 + " parses to " + date.toString());
      } catch (ParseException e) {
         System.out.println("invalid: " + str1 );
      }
 
     try {
         Date date = sdf.parse(str2);
         System.out.println(str2 + " parses to " + date.toString());
      } catch (ParseException e) {
         System.out.println("invalid: " + str2 );
      }
 
 
   }
}

Output:
$ java TestDate
01/28/15 parses to Wed Jan 28 00:00:00 EST 2015
invalid: 124/12/12

Calculating the frequency of the sum of the rolling of a pair of dice.

Question:
Java program to calculate the frequency of the sum of the rolling of a pair of dice.

Code:
public class RollDice {
 
   public static void main(String[] args) {
 
      int frequency[] = new int[13];
 
      int total=0;
      for (int roll = 1; roll <= 5000; roll++) {
         total = 1 + (int) (Math.random() * 6);
         total = total + 1 + (int) (Math.random() * 6);
         frequency[total] = frequency[total] + 1;
      }
 
 
      System.out.println("Total\tFrequency");
      for(int n=2;n<frequency.length;n++){
         System.out.println(n + "\t" + frequency[n]);
      }
 
   } 
}

Output:
$ java RollDice
Total Frequency
2 141
3 275
4 424
5 579
6 674
7 821
8 705
9 560
10 410
11 268
12 143

Printing Histogram Using Array

Question:
How to print a histogram using an array?

Code:
public class Histogram {  
 
  public static void main(String[] args) { 
 
    int array[] = {4,10,7,15,12,3,7,10,6,19};
 
    String output = "Element\tValue\tHistogram";
 
    for ( int counter = 0; counter < array.length; counter++ ) {
      output += "\n" + counter + "\t" + array[ counter ] + "\t";
 
      for ( int stars = 0; stars < array[ counter ]; stars++ ) {
        output += "*";   
      }
    }
    System.out.println(output);
  } 
} 

Output:
$ java Histogram
Element Value Histogram
0 4 ****
1 10 **********
2 7 *******
3 15 ***************
4 12 ************
5 3 ***
6 7 *******
7 10 **********
8 6 ******
9 19 *******************

Java program to calculate how much you would weigh on the moon.

Question:
Java program to calculate how much you would weigh on the moon?

Code:
import java.util.Scanner;
 
public class MoonWeight {
  public static void main(String[] args) {
 
    Scanner input = new Scanner(System.in);
 
    System.out.print("Enter your weight: ");
    double normalWeight = input.nextDouble();
 
    double weightOnMoon = normalWeight * (16.5 / 100);
    System.out.println("Your weight on moon is: "  + weightOnMoon );
  }
}
 

Output:
$ java MoonWeight
Enter your weight: 100
Your weight on moon is : 16.5

Enabling SSL v3.0 in java 8

Question:
Enabling SSL v3.0 in java 8

Answer:
Starting with the January 20, 2015 Critical Patch Update releases (JDK 8u31, JDK 7u75, JDK 6u91 and above) the Java Runtime Environment has SSLv3 disabled by default.

It should be noted that SSLv3 is obsolete and should no longer be used.
See: http://www.oracle.com/technetwork/java/javase/8u31-relnotes-2389094.html

If you must re-enable SSLv3.0 on either 8u31, 7u75, 6u91 all you have to do is comment out the following line in JRE_HOME/lib/security/java.security:
  jdk.tls.disabledAlgorithms=SSLv3

Code:
import javax.net.ssl.*;
 
public class SocketProtocols {
 
  public static void main(String[] args) throws Exception {
 
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket soc = (SSLSocket) factory.createSocket();
 
    // Returns the names of the protocol versions which are
    // currently enabled for use on this connection.
    String[] protocols = soc.getEnabledProtocols();
 
    System.out.println("Enabled protocols:");
    for (String s : protocols) {
      System.out.println(s);
    }
 
  }
} 

Output:
Before enabling SSL 3.0

$ /jdk1.8.0_31/bin/java SocketProtocols
Enabled protocols:
TLSv1
TLSv1.1
TLSv1.2



After enabling SSL 3.0

$ /jdk1.8.0_31/bin/java SocketProtocols
Enabled protocols:
SSLv3
TLSv1
TLSv1.1
TLSv1.2