Friday, April 1, 2016

Java I/O Examples : How To Delete Temporary File

Intro


This examples will demonstrates how to delete a temporary file using Java program. To delete it, you can use one of the following method:
  • deleteOnExit(), delete temporary file when program is terminated or exited.
  • delete(), delete temporary file imediately,

Examples


package com.freesamplecode.java.io;

import java.io.File;
import java.io.IOException;

public class DeleteTemporaryFileDemo {
	public static void main(String[] args){
		
		try {
			
			// create temporary file "test.tmp"
			
			File tempFile = File.createTempFile("test", ".tmp");
			
			
			// delete temporary file when the program is terminated or existed
			
			tempFile.deleteOnExit();
			
			//delete temporary file immediately
			
            //tempFile.delete();
			
			System.out.println("Temporary file "+tempFile.getName() + " is successfully deleted");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


Output


Temporary file test1195400416650249998.tmp is successfully deleted

How To Delete Temporary File In Java

Java I/O Examples : How To Generate A File Checksum Value With MD5 Algorithm

Intro


This examples will demonstrates how to generate a file checksum with MD5 algorithm. To generate it, you should use MessageDigest class. This output is in the hexadecimal format.

Examples


package com.freesamplecode.java.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileChecksumDemo {
	public static void main(String[] args){
		
		//Step 1 : prepare file name
		String fileName = "D:/temp/test/file_test.txt";
		
		try {
			
			//Step 2 : create MD5 MessageDigest object
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			
			// Step 3 : read data
			FileInputStream fis = new FileInputStream(fileName);
			
			byte[] bytedata = new byte[1024];
			
			int read = 0;
			
			while((read = fis.read(bytedata)) != -1){
				messageDigest.update(bytedata, 0, read);
			}
			
			//Step 4: calculate digest bytedata 
			byte[] bytemd = messageDigest.digest();
			
			//Step 5 : convert into hex format
			
			StringBuffer sb = new StringBuffer("");
			
			for(int i = 0; i < bytemd.length; i++){
				sb.append(Integer.toString((bytemd[i] & 0xff) + 0x100, 16).substring(1));
			}
			
			//Step 6 : Display to console
			System.out.println("Result.....");
			System.out.println(fileName+" : " + sb.toString());
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

Output


Result.....
D:/temp/test/file_test.txt : c16665a5040f355d62eea6d2d5274c83

Screenshot

How To Generate A File Checksum Value With MD5 Algorithm In Java


Java Collection Examples : How To Remove Duplicate Elements From An Array

Intro


This examples will demonstrates how to remove duplicate elements from an array. To get it, you have to convert an array into a Set collection first.

Examples


package com.freesamplecode.java.array;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateElementDemo {
	public static void main(String[] args){
		
		   // Step 1:  Prepare a duplicate array
		   String[] strArray = { "A", "B", "B", "C", "A", "D", "B", "A", "B", "D" };
		   
		   System.out.println("Original Array : "+Arrays.toString(strArray));
		   
		   // Step 2 : Convert an array to list
		   List list = Arrays.asList(strArray);
		   
		   // Step 3 : Create a Set object from list
		   Set set = new HashSet(list);
		   
		   // Step 4 : Create an array object to hold values from set
		   String[] newArray = new String[set.size()];
		   
		   // Step 5 : Convert a Set into an Array
		   set.toArray(newArray);
		   
		   // Step 6 : Display value after removing duplicate to console
		   System.out.print("After removing duplicates: "+Arrays.toString(newArray));
		   
		   
		   
	}
}

Output


Original Array : [A, B, B, C, A, D, B, A, B, D]
After removing duplicates: [D, A, B, C]

Screenshot


How To Remove Duplicate Elements From An Array In Java

Java Date & Time Examples : How To Convert A String Into Date

Intro


This examples will demonstrates how to convert a string into date object. It is very quite simple, you can use SimpleDateFormat.parse() method to parse a string format into date object.

Examples


package com.freesamplecode.java.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertStringToDateDemo {
 public static void main(String[] args){
  String dateString1 = "8-Jan-2016";
  String dateString2 = "08/01/2016";
  String dateString3 = "Jan 8, 2016";
  
  SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy");
  SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
  SimpleDateFormat sdf3 = new SimpleDateFormat("MMM dd, yyyy");
  
  try {
   Date date1 = sdf1.parse(dateString1);
   System.out.println(date1);
   
   Date date2 = sdf2.parse(dateString2);
   System.out.println(date2);
   
   Date date3 = sdf3.parse(dateString3);
   System.out.println(date3);
   
   
  } catch (ParseException e) {
   e.printStackTrace();
  }
  
 }
}

Output


Fri Jan 08 00:00:00 ICT 2016
Fri Jan 08 00:00:00 ICT 2016
Fri Jan 08 00:00:00 ICT 2016

Screenshot


How To Convert A String Into Date In Java





Wednesday, March 30, 2016

Java Date & Time Examples : How To Convert Date To String

Intro


This examples will demonstrates how to convert a date object into string format. It is very quite simple, you can use SimpleDateFormat.format() method to format a date object into specify format.

Examples


package com.freesamplecode.java.datetime;

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

public class ConvertDateToStringDemo {
 public static void main(String[] args){
  
  //get today
  Date today = Calendar.getInstance().getTime();
  
  //create a simple date format object to specify string format
  SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss");
  
  //display today in string format
  System.out.println("Today is : "+sdf.format(today));
 }
}

Output


Today is : 31/03/2016 05.58.21

Screenshot

How To Convert Date To String In Java


Java I/O Examples : How To Move A File To Another Directory

Intro


This examples will demonstrates how to move a file from one directory to another directory. It's very tricky, we will use File.renameTo() method to move it.

Examples


package com.freesamplecode.java.io;

import java.io.File;

public class MoveFileDemo {
 public static void main(String[] args){
  
  String fileName = "test.txt";
  
  //source directory
  File sourceDir = new File("D:/temp/sourcedir/"+fileName);
  
  //destination directory
  File destDir = new File("D:/temp/destdir/"+fileName);
  
  if(sourceDir.renameTo(destDir)){
   System.out.println("Move File operation is successfully...");
  }else{
   System.out.println("Failed to execute move file operation, please try again...");
  }
 }
}


Output


Move File operation is successfully...

Screenshot


before move file

How To Move A File To Another Directory In Java

after move file

How To Move A File To Another Directory In Java

Java Examples : How To Get Home Directory

Intro


This examples will demonstrates how to display an user home directory. It is quite simple, we can use System.getProperty() method with "user.home" parameter.

Examples


package com.freesamplecode.java.basic;

public class GetUserHomeDirectoryDemo {
 public static void main(String[] args){
  String homeDirectory = System.getProperty("user.home");
  
  System.out.println("Home Directory : "+homeDirectory);
 }
}


Output


Home Directory : C:\Users\Dev

Screenshot

How To Get Home Directory In Java

Tuesday, March 29, 2016

Java I/O Examples : How To Write An Object To File

Intro


This examples will demonstrates how to write a Java object into file using serialization method. To use serialization method, your Java class have to implement the Serializable interface.

Examples


Employee.java

public class Employee implements Serializable{
 /**
  * 
  */
 private static final long serialVersionUID = 8836890329708390627L;
 
 private long id;
 private String name;
 private String sex;
 private String placeOfBirth;
 private Date dateOfBirth;
 
 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getSex() {
  return sex;
 }
 
 public void setSex(String sex) {
  this.sex = sex;
 }
 
 public String getPlaceOfBirth() {
  return placeOfBirth;
 }
 
 public void setPlaceOfBirth(String placeOfBirth) {
  this.placeOfBirth = placeOfBirth;
 }
 
 public Date getDateOfBirth() {
  return dateOfBirth;
 }
 
 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }
 
}

WriteObjectToFileDemo.java

public class WriteObjectToFileDemo {
 public static void main(String[] args){
  //create an Employee object
  Employee employee = new Employee();
  employee.setId(879829);
  employee.setName("Nursalim");
  employee.setPlaceOfBirth("Brebes");
  employee.setDateOfBirth(new Date());
  employee.setSex("M");
  
  try {
   FileOutputStream fos = new FileOutputStream("c:/TEMP/employee.ser");
   
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   oos.writeObject(employee);
   oos.close();
   
   System.out.println("Done!, Successfully write object to file...");
  } catch (FileNotFoundException e) {
   System.err.println("File not found");
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println("Error encountered...");
   e.printStackTrace();
  }
  
 }
}

Output


Done!, Successfully write object to file...

Screenshot


How To Write An Object To File In Java

Java I/O Examples : How To Read An Object From File

Intro


This examples will demonstrates how to read a Java object from file which means deserialization.

Examples


Employee.java

package com.freesamplecode.java.io;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable{
 /**
  * 
  */
 private static final long serialVersionUID = 8836890329708390627L;
 
 private long id;
 private String name;
 private String sex;
 private String placeOfBirth;
 private Date dateOfBirth;
 
 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getSex() {
  return sex;
 }
 
 public void setSex(String sex) {
  this.sex = sex;
 }
 
 public String getPlaceOfBirth() {
  return placeOfBirth;
 }
 
 public void setPlaceOfBirth(String placeOfBirth) {
  this.placeOfBirth = placeOfBirth;
 }
 
 public Date getDateOfBirth() {
  return dateOfBirth;
 }
 
 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }
 
}

ReadObjectFromFileDemo.java

public class ReadObjectFromFileDemo {
 public static void main(String[] args){
  try {
   FileInputStream fis = new FileInputStream("c:/TEMP/employee.ser");
   ObjectInputStream ois = new ObjectInputStream(fis);
   Employee employee = (Employee) ois.readObject();
   
   System.out.println("Read Employee data...");
   System.out.println("ID : " +employee.getId());
   System.out.println("Name : " +employee.getName());
   System.out.println("Place of Birth : " +employee.getPlaceOfBirth());
   System.out.println("Date of Birth : " +employee.getDateOfBirth());
   System.out.println("Gender : " +employee.getSex());
   
   ois.close();
  } catch (FileNotFoundException e) {
   System.err.println("File not found");
   e.printStackTrace();
  } catch (IOException e) {
   System.err.println("Error when accessing file");
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}

Output


Read Employee data...
ID : 879829
Name : Nursalim
Place of Birth : Brebes
Date of Birth : Tue Mar 29 15:32:25 ICT 2016
Gender : M

Screenshot

How To Read An Object From File In Java


Java I/O Examples : How To Get Temporary File Path

Intro


This examples will demonstrates how to get or display temporary file path in your operating system (os).

Examples


package com.freesamplecode.java.io;

import java.io.File;
import java.io.IOException;

public class GetTemporaryFilePathDemo {
 public static void main(String[] args){
  try {
   
   //step 1. create a temporary file
   File file = File.createTempFile("tempfile", ".tmp");
   
   //step 2. get absolute path
   String absolutePath = file.getAbsolutePath();
   
   //step 3. get temporary file path
   String temporaryFilePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
   
   //step 4. print to console
   System.out.println("Absolute path : "+absolutePath);
   System.out.println("Temporary File path : "+temporaryFilePath);
   
  } catch (IOException e) {
   System.err.println("Error when creating a file..");
   e.printStackTrace();
  }
  
 }
}

Output


Absolute path : C:\Users\Dev\AppData\Local\Temp\tempfile3944253553416804097.tmp
Temporary File path : C:\Users\Dev\AppData\Local\Temp

Screenshot

How To Get Temporary File Path In Java

Java JSON Examples : How To Read JSON File Using JSON Simple

Intro


This examples will demonstrates how to read JSON file using JSON Simple. To read a JSON file, you can use JSONParser class to read each of the values.

Examples


package com.freesamplecode.java.json.simple;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ReadJSONFileDemo {
 public static void main(String[] args){
  JSONParser jsonParser = new JSONParser();
  String fileName = "C:/TEMP/test.json";
  
  try {
   Object obj = jsonParser.parse(new FileReader(fileName));
   
   JSONObject jsonObject = (JSONObject) obj;
   
   String name = (String) jsonObject.get("name");
   String country = (String) jsonObject.get("country");
   
   System.out.println("Name : "+name);
   System.out.println("Country : "+country);
   System.out.print("Hobbies : ");
   
   JSONArray jsonArray = (JSONArray) jsonObject.get("hobbies");
   Iterator it = jsonArray.iterator();
   while(it.hasNext()){
    System.out.print(it.next()+", ");
   }
   
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ParseException e) {
   e.printStackTrace();
  }
  
 }
}

Output


Name : Nursalim
Country : Indonesia
Hobbies : Reading, Coding, Traveling, 

Screenshoot


How To Read JSON File Using JSON Simple In Java

Java I/O Examples : How To Read A Text File Line By Line

Intro


This examples will demonstrates how to read a text file line by line. To get this, you can use readLine() method in the BufferedReader class.

Examples


package com.freesamplecode.java.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileByLineDemo {
 public static void main(String[] args){
  
  String strLine = "";
  String fileName = "D:/temp/test/file_test.txt";
  try {
   
   BufferedReader br = new BufferedReader(new FileReader(fileName));
   while((strLine = br.readLine()) != null){
    System.out.println(strLine);
   }
  } catch (FileNotFoundException e) {
   System.err.print("Unable to find file :"+fileName);
   e.printStackTrace();
  } catch (IOException e) {
   System.err.print("Error encountered when accessing file "+fileName);
   e.printStackTrace();
  }
  
 }
}

Output


Hello,
Welcome to http://free-samplecode.blogspot.com
May this website useful for you.

Thanks,

Admin

Screenshoot


How To Read A Text File Line By Line In Java

Monday, March 28, 2016

Java Examples : How To Display All Environment Variables

Intro


This examples will demonstrates how to display all environment variables using Java program. To display it, you can use System.getEnv() method that will return a collections of environment variables in your system.


Examples


package com.freesamplecode.java.basic;

import java.util.Map;
import java.util.Set;

public class DisplayEnvVariableDemo {
 public static void main(String[] args){
  Map envVar = System.getenv();
  
  Set keySet = envVar.keySet();
  
  for(String key : keySet){
   String value = (String) envVar.get(key);
   
   System.out.println("[ " + key + " ] : "+value);
  }
 }
}

Output


[ USERPROFILE ] : C:\Users\Dev
[ ProgramData ] : C:\ProgramData
[ PATHEXT ] : .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.RB;.RBW;.PY
[ windows_tracing_logfile ] : C:\BVTBin\Tests\installpackage\csilogfile.log
[ ORACLE_HOME ] : D:\app\Dev\11g
[ JAVA_HOME ] : C:\Program Files (x86)\Java\jdk1.7.0_03
[ TFS_DIR ] : C:\Program Files\ThinkVantage Fingerprint Software\
[ ProgramFiles(x86) ] : C:\Program Files (x86)
[ windows_tracing_flags ] : 3
[ TEMP ] : C:\Users\Dev\AppData\Local\Temp
[ SystemDrive ] : C:
[ ProgramFiles ] : C:\Program Files
[ Path ] : C:\Perl64\site\bin;C:\Perl64\bin;C:\Ruby22-x64\bin;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;D:\app\Dev\11g\bin;C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\Program Files\Broadcom\Broadcom 802.11 Network Adapter\Driver;;;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;;;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Lenovo\Access Connections\;C:\Program Files (x86)\Lenovo\Password Manager\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;D:\Installer\eclipse-jee-indigo-SR2-win32\eclipse\plugins\org.apache.ant_1.8.2.v20120109-1030\bin;C:\Program Files (x86)\Java\jdk1.6.0\bin;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\TortoiseHg\;C:\Program Files\nodejs\;C:\Users\Dev\AppData\Roaming\npm
[ HOMEDRIVE ] : C:
[ PROCESSOR_REVISION ] : 2a07
[ USERDOMAIN ] : MOBILE214
[ ALLUSERSPROFILE ] : C:\ProgramData
[ ProgramW6432 ] : C:\Program Files
[ PROCESSOR_IDENTIFIER ] : Intel64 Family 6 Model 42 Stepping 7, GenuineIntel
[ SESSIONNAME ] : Console
[ TMP ] : C:\Users\Dev\AppData\Local\Temp
[ pythonpath ] : C:\Python34;C:\Python34\Scripts;
[ VISUALSVN_SERVER ] : C:\Program Files (x86)\VisualSVN Server\
[ CommonProgramFiles ] : C:\Program Files\Common Files
[ ACPath ] : C:\Program Files (x86)\Lenovo\Access Connections\
[ =:: ] : ::\
[ LOGONSERVER ] : \\MOBILE214
[ PROCESSOR_ARCHITECTURE ] : AMD64
[ FP_NO_HOST_CHECK ] : NO
[ OS ] : Windows_NT
[ TVT ] : C:\Program Files (x86)\Lenovo
[ HOMEPATH ] : \Users\Dev
[ PROCESSOR_LEVEL ] : 6
[ CommonProgramW6432 ] : C:\Program Files\Common Files
[ ANT_HOME ] : D:\Installer\eclipse-jee-indigo-SR2-win32\eclipse\plugins\org.apache.ant_1.8.2.v20120109-1030
[ LOCALAPPDATA ] : C:\Users\Dev\AppData\Local
[ COMPUTERNAME ] : MOBILE214
[ windir ] : C:\Windows
[ SystemRoot ] : C:\Windows
[ NUMBER_OF_PROCESSORS ] : 4
[ USERNAME ] : Dev
[ PUBLIC ] : C:\Users\Public
[ PSModulePath ] : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
[ CommonProgramFiles(x86) ] : C:\Program Files (x86)\Common Files
[ ComSpec ] : C:\Windows\system32\cmd.exe
[ APPDATA ] : C:\Users\Dev\AppData\Roaming


Screenshot

How To Display All Environment Variables In Java


Java Bean Examples : How To Display All Property Names Of A Bean

Intro


This examples will demonstrates how to display all property names of a bean using BeanInfo class.

Examples


Employee.java

package com.freesamplecode.java.bean;

import java.io.Serializable;
import java.util.Date;

public class Employee implements Serializable{
 /**
  * 
  */
 private static final long serialVersionUID = 8836890329708390627L;
 
 private long id;
 private String name;
 private String sex;
 private String placeOfBirth;
 private Date dateOfBirth;
 
 public long getId() {
  return id;
 }
 
 public void setId(long id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getSex() {
  return sex;
 }
 
 public void setSex(String sex) {
  this.sex = sex;
 }
 
 public String getPlaceOfBirth() {
  return placeOfBirth;
 }
 
 public void setPlaceOfBirth(String placeOfBirth) {
  this.placeOfBirth = placeOfBirth;
 }
 
 public Date getDateOfBirth() {
  return dateOfBirth;
 }
 
 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }
 
}

GetListPropertyNameBeanDemo.java

package com.freesamplecode.java.bean;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class GetListPropertyNameBeanDemo {
 public static void main(String[] args){
  BeanInfo beanInfo;
  try {
   beanInfo = Introspector.getBeanInfo(Employee.class);
   PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors();
   
   for(PropertyDescriptor pd : propertyDescriptor){
    System.out.println("Property Name : "+pd.getName());
   }
   
  } catch (IntrospectionException e) {
   e.printStackTrace();
  }
  
  
  
 }
}


Output


Property Name : class
Property Name : dateOfBirth
Property Name : id
Property Name : name
Property Name : placeOfBirth
Property Name : sex

Screenshot

How To Display All Property Names Of A Bean In Java


Java Logging Examples : How To Compare Log Level Severity

Intro


This examples will demonstrates how to compare log level severity for each log level. The java.util.logging.Level class has an intValue() method that return the integer value of Level‘s severity.

Examples


package com.freesamplecode.java.logging;

import java.util.logging.Level;

public class CompareLogLevelSeverityDemo {
 public static void main(String[] args){
  Level info = Level.INFO;
        Level warning = Level.WARNING;
        Level config = Level.CONFIG;
        Level finest = Level.FINEST;
        
        if (info.intValue() < warning.intValue()) {
            System.out.println(info + "(" + info.intValue() + ") is less severe than " +
                    warning + "(" + warning.intValue() + ")");
        }

        if (finest.intValue() < info.intValue()) {
            System.out.println(finest + "(" + finest.intValue() + ") is less severe than " +
                    info + "(" + info.intValue()+ ")");
        }
        
        if (config.intValue() < warning.intValue()) {
            System.out.println(config + "(" + config.intValue() + ") is less severe than " +
                    warning + "(" + warning.intValue()+ ")");
        }
 }
}

Output


INFO(800) is less severe than WARNING(900)
FINEST(300) is less severe than INFO(800)
CONFIG(700) is less severe than WARNING(900)

Screenshot


How To Compare Log Level Severity In Java


Java Logging Examples : How To Limit The Size Of Log File

Intro

This examples will demonstrates how to limit size of log file just one file.

Examples


package com.freesamplecode.java.logging;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;

public class LimitLogFileDemo {
 
 //set maximal log file in 1 KB
 public static final int FILE_SIZE = 1 * 1024;
 
 public static void main(String[] args){
  Logger logger = Logger.getLogger(LimitLogFileDemo.class.getName());
  
  
  try {
   //create an object handler
   FileHandler handler = new FileHandler("limitlog.log", FILE_SIZE, 1, true);
   
   logger.addHandler(handler);
  } catch (SecurityException | IOException e) {
   e.printStackTrace();
  }
  
  logger.info("Test info");
        logger.warning("Test warning");
        logger.severe("Test severe");
   
 }
}

Output


Mar 29, 2016 5:23:38 AM com.freesamplecode.java.logging.LimitLogFileDemo main
INFO: Test info
Mar 29, 2016 5:23:38 AM com.freesamplecode.java.logging.LimitLogFileDemo main
WARNING: Test warning
Mar 29, 2016 5:23:38 AM com.freesamplecode.java.logging.LimitLogFileDemo main
SEVERE: Test severe

Screenshoot


How To Limit The Size Of Log File In Java

Sunday, March 27, 2016

Java Networking Examples : How To Get HTTP Header Information of URL

Intro

This examples will demonstrates how to get header information of URL such as status code, response code, content type, and etc.

To get a header information of URL, you can use HttpURLConnection.getHeaderFields() method.

Examples


package com.freesamplecode.java.networking;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class GetHeaderInformationURLDemo {
 public static void main(String[] args){
  
  try {
   //create URL object
   URL url = new URL("http://free-samplecode.blogspot.com/p/java.html");
   
   //open URL connection
   HttpURLConnection httpUrlConnection =  (HttpURLConnection) url.openConnection();
   
   //get all URL header informations
   Map headerField = httpUrlConnection.getHeaderFields();
   
   Set set = headerField.entrySet();
   
   Iterator it = set.iterator();
   
   while(it.hasNext()){
    System.out.println(it.next());
   }
   

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Output


null=[HTTP/1.1 200 OK]
Expires=[Sun, 27 Mar 2016 13:31:17 GMT]
X-XSS-Protection=[1; mode=block]
Last-Modified=[Sun, 27 Mar 2016 13:15:17 GMT]
Connection=[Keep-Alive]
Server=[GSE]
X-Content-Type-Options=[nosniff]
Cache-Control=[private, max-age=0]
Date=[Sun, 27 Mar 2016 13:31:17 GMT]
Vary=[Accept-Encoding]
Transfer-Encoding=[chunked]
Content-Type=[text/html; charset=UTF-8]
Accept-Ranges=[none]

Screenshot

How To Get HTTP Header Information of URL In Java

Java Networking Examples : How To Display Source Code Of A Web Page Using URLConnection

Intro

This examples will demonstrates how to display source code of a web page using URLConnection class.

Examples


package com.freesamplecode.java.networking;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GetSourceCodeWebDemo {
 public static void main(String[] args){
  try {
   
   //create URL object
   URL url = new URL("http://free-samplecode.blogspot.com/p/java.html");
   
   //open URL connection
   URLConnection urlConnection = url.openConnection();
   
   //get stream of URL 
   InputStream is = urlConnection.getInputStream();
   int i = 0;
   while((i = is.read()) != -1){
    System.out.print((char)i);
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }
}

Output

How To Display Source Code Of A Web Page Using URLConnection

Java I/O Examples : How To Set File Permissions

Intro


This examples will demonstrates how to set file permissions using Java program. To set file permissions, you can use the following methods, are File.setExecutable(), File.setReadable(), and File.setWritable() methods.

Examples


package com.freesamplecode.java.io;

import java.io.File;

public class SetFilePermissionDemo {
 public static void main(String[] args){
  File file = new File("D:/temp/test.sh");
  System.out.println("Before set permission...");
  System.out.println("Can execute? : "+file.canExecute());
  System.out.println("Can Write? : "+file.canWrite());
  System.out.println("Can Read? : "+file.canRead());
  
  file.setExecutable(true);
  file.setWritable(false);
  file.setReadable(true);
  
  System.out.println("\n After set permission....");
  System.out.println("Can execute? : "+file.canExecute());
  System.out.println("Can Write? : "+file.canWrite());
  System.out.println("Can Read? : "+file.canRead());
 }
}


Output


Before set permission...
Can execute? : true
Can Write? : false
Can Read? : true

After set permission....
Can execute? : true
Can Write? : false
Can Read? : true

Screenshot

How To Set File Permissions In Java

Java Examples : How To Use Final Variable

Intro


This examples, will demonstrates how to use final variable in Java program. Final variable is used to declares a constants in Java program. Once you created, a final variable cannot change this value.

Examples


package com.freesamplecode.java.basic;

public class FinalVariableDemo {
 public static void main(String[] args){
  final int HOUR_OF_DAY = 24;
  
  System.out.println("Hours in one day are : "+HOUR_OF_DAY);
 }
}

Output


Hours in one day are : 24

Screenshot

How To Use Final Variable