Log in
updated 11:29 AM UTC, May 4, 2016

Java NIO file Watcher service example

Here is a small example to listen to the folder changes of a filesystem and notify the change to the user.

 

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

import au.gov.ehp.common.Config;
import au.gov.ehp.common.Proda.CreateFileThread;

public class FolderNotification {

	public void waitTillFile() throws IOException,
			InterruptedException, Exception {

		Thread createFileThread = new Thread(new CreateFileThread());
		createFileThread.start();

		Path path = Paths.get("C:\\dev\\git\\automation\\");

		WatchService watchService = FileSystems.getDefault().newWatchService();
		WatchKey watchKey = path.register(watchService, ENTRY_CREATE,
				ENTRY_DELETE, ENTRY_MODIFY);
		WatchKey key;
		System.out.println("Now Waiting for the changes in the folder: " + path.getFileName());
		key = watchService.take();
		List<WatchEvent<?>> events = key.pollEvents();

		for (WatchEvent event : events) {
			if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
				System.out.println("Created: " + event.context().toString());
				break;
			} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
				System.out.println("Delete: " + event.context().toString());
				break;
			} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
				System.out.println("Modify: " + event.context().toString());
				break;
			} else {
				System.out.println("Some other type "
						+ event.context().toString());
				break;
			}
		}
		key.reset();
		watchService.close();
		System.out.println("done. Exiting the service");
	}
	
	public static void main(String args[]) throws IOException, InterruptedException, Exception {
		new FolderNotification().waitTillFile();
		System.exit(0);
	}

}

 

Here is the output:

Now Waiting for the changes in the folder: automation

Now create a folder or delete an existing folder or modify the folder.

Delete: New folder
done. Exiting the service

Add a comment (2)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 1306

Find adjacent colors in an image using JavaCV

Here is a small program to find adjacent colours in an image using JAVA CV based on OpenCV

 

import static org.bytedeco.javacpp.opencv_imgcodecs.cvLoadImage;
import static org.bytedeco.javacpp.opencv_core.cvGet2D;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.bytedeco.javacpp.opencv_core.CvScalar;
import org.bytedeco.javacpp.opencv_core.IplImage;

public class ImageProcessing {
	
	class RGB {
	

		double red, green, blue;
		
		public RGB(double red, double green, double blue) {
			this.red = red;
			this.green = green;
			this.blue = blue;
		}
		
		public double red() {
			return red;
		}
		
		public double green() {
			return green;
		}
		
		public double blue() {
			return blue;
		}

		private ImageProcessing getOuterType() {
			return ImageProcessing.this;
		}
		
		


		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + getOuterType().hashCode();
			long temp;
			temp = Double.doubleToLongBits(blue);
			result = prime * result + (int) (temp ^ (temp >>> 32));
			temp = Double.doubleToLongBits(green);
			result = prime * result + (int) (temp ^ (temp >>> 32));
			temp = Double.doubleToLongBits(red);
			result = prime * result + (int) (temp ^ (temp >>> 32));
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			RGB other = (RGB) obj;
			if (!getOuterType().equals(other.getOuterType()))
				return false;
			if (Double.doubleToLongBits(blue) != Double
					.doubleToLongBits(other.blue))
				return false;
			if (Double.doubleToLongBits(green) != Double
					.doubleToLongBits(other.green))
				return false;
			if (Double.doubleToLongBits(red) != Double
					.doubleToLongBits(other.red))
				return false;
			return true;
		}
		
		@Override
		public String toString() {
			
			return "[ R: " + red() + " G: " + green() + " B: " + blue() + " ] ";
			
		}
	}
	
	Map<RGB, List<RGB>> adjacentColors = new HashedMap();
	
	
	
	
	 public static void main(String[] args) throws Exception {
		 
		 
		new ImageProcessing().processImages();
		 
	 }




	private void processImages() {
		IplImage rawImage  = cvLoadImage("amend.png");
		 ByteBuffer buffer = rawImage.getByteBuffer();
		 
		 
		 
		 for(int h = 0; h < rawImage.height();h++) {
			 for(int w = 0; w<rawImage.width();w++) {

				 CvScalar s= cvGet2D(rawImage,h,w);
				 int nextEleOnSameLevel = w + 1;
				 int nextEleOnLowerLevel = h +1;
				 
				 RGB rgb = new RGB(s.val(2),s.val(1),s.val(0));
				 
				 if(nextEleOnSameLevel < rawImage.width()) {
					 s= cvGet2D(rawImage,h,nextEleOnSameLevel);
					 RGB nextRGB = new RGB(s.val(2),s.val(1),s.val(0));
					 if(!rgb.equals(nextRGB)) {
						 addToAdjacentColors(rgb, nextRGB);
					 }
				 }
				 
				 if(nextEleOnLowerLevel < rawImage.height()) {
					 s= cvGet2D(rawImage,nextEleOnLowerLevel,w);
					 RGB lowerRGB = new RGB(s.val(2),s.val(1),s.val(0));
					 if(!rgb.equals(lowerRGB)) {
						 addToAdjacentColors(rgb, lowerRGB);
					 }
				 }
				 
			 }
		 }
		 
		 for (Map.Entry<RGB, List<RGB>> entry : adjacentColors.entrySet())
		 {
		     System.out.println(entry.getKey() + " / " + entry.getValue());
		 }
	}




	private void addToAdjacentColors(RGB rgb, RGB nextRGB) {
		List<RGB> colors = adjacentColors.get(rgb);

		if (colors != null) {
			addColorIfNotExists(colors, nextRGB);
		} else {
			List<RGB> rgbColors = new ArrayList<ImageProcessing.RGB>();
			rgbColors.add(nextRGB);
			adjacentColors.put(rgb,rgbColors);
		}
	}


	private void addColorIfNotExists(List<RGB> colors, RGB nextRGB) {
		for(RGB rgb:colors) {
			if(rgb.equals(nextRGB)) {
				return;
			}
		}
		colors.add(nextRGB);
	}
}

Add a comment (1)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 1105

How to read from a CSV file, Sort the contents and populate a JTable

Here is a small example to read a CSV file and sort based on a column and then populate the JTable (Swing component).

I feel the code is self explanatory , if not please let me know in the comments section will try to add the comments where required.

 

Main Program:

package test;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class CSVTable extends JFrame {

	private static final int NUMBER_OF_COLUMNS = 4;
	private static final String AEKOS_LINK = "Link";
	private static final String LONG = "Long";
	private static final String LAT = "Lat";
	private static final String CRS = "CRS";

	private Logger logger = Logger.getLogger(this.getName());
	private List<TableDataModel> tableList = new ArrayList<TableDataModel>();
	/**
	 * Default Serialization Version
	 */
	private static final long serialVersionUID = 1L;

	public CSVTable() {
		super();
		InputStream stream = this.getClass().getResourceAsStream("CSV_1.csv");
		readAndUpdateTableDataModel(stream);

		Object[] columnNames = new Object[NUMBER_OF_COLUMNS];
		columnNames[0] = AEKOS_LINK;
		columnNames[1] = LONG;
		columnNames[2] = LAT;
		columnNames[3] = CRS;

		DefaultTableModel model = new DefaultTableModel(columnNames,0);

		populateModel(model);

		JTable table = new JTable(model);
			
		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setBounds(new Rectangle(new Dimension(400, 300)));
		
		this.getContentPane().add(scrollPane);

	}

	private void populateModel(DefaultTableModel model) {
		for (int i = 0; i < tableList.size(); i++) {
			model.addRow(this.tableList.get(i).getDataAsObjectList());
		}
	}

	public static void main(String args[]) {
		final CSVTable table = new CSVTable();
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				table.setTitle("CSV Table");
				table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				table.pack();
				table.setVisible(true);
			}
		});

	}

	public void readAndUpdateTableDataModel(InputStream in) {

		Scanner scan = new Scanner(in);

		while (scan.hasNext()) {
			String rowValue = scan.nextLine();
			seperateAndPopulate(tableList, rowValue);
		}
		Collections.sort(tableList);

	}

	private void seperateAndPopulate(List<TableDataModel> tableList,
			String rowValue) {
		String splitValue[] = rowValue.split(",");
		if (splitValue.length == NUMBER_OF_COLUMNS) {
			if (splitValue[0].equals(AEKOS_LINK)) {
				return;
			}
			TableDataModel model = TableDataModel.newInstance(splitValue[0],
					splitValue[1], splitValue[2], splitValue[3]);
			tableList.add(model);
		} else {
			logger.log(Level.SEVERE, "Issue with data");
		}
	}

}

 

TableDataModel:

package test;

public class TableDataModel implements Comparable<TableDataModel> {
	
	private String aekoLink;
	private String longData;
	private String latData;
	private String cRS;

	private TableDataModel() {
		//dont allow creation of Object without elements
	}
	
	public String getAekoLink() {
		return aekoLink;
	}

	public void setAekoLink(String aekoLink) {
		this.aekoLink = aekoLink;
	}

	public String getLongData() {
		return longData;
	}

	public void setLongData(String longData) {
		this.longData = longData;
	}

	public String getLatData() {
		return latData;
	}

	public void setLatData(String latData) {
		this.latData = latData;
	}

	public String getcRS() {
		return cRS;
	}

	public void setcRS(String cRS) {
		this.cRS = cRS;
	}

	public static TableDataModel newInstance(String aekoLink,String longData, String latData, String cRs ) {
		TableDataModel model = new TableDataModel();
		model.setAekoLink(aekoLink);
		model.setLongData(longData);
		model.setLatData(latData);
		model.setcRS(cRs);
		return model;
	}

	@Override
	public int compareTo(TableDataModel o) {
		return this.getAekoLink().compareTo(o.getAekoLink());
	}
	
	public Object[] getDataAsObjectList() {
		Object[] columnVals = new Object[4];
		columnVals[0] = this.getAekoLink();
		columnVals[1] = this.getLongData();
		columnVals[2] = this.getLatData();
		columnVals[3] = this.getcRS();
		return columnVals;
	}
	
}

 

CSV File:

LINK TO CSV File

Add a comment (3)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 2493

Difference Between Swing and AWT

SwingAWT
Portability: Pure Java design provides for great advantage for portability - works more consistently across many platforms

Portability: use of native peers creates platform specific limitations. Some components may not function as expected in different platforms.

Features: Swing supports a wider range of features including icons and pop-up tool-tips for components. Features: AWT components do not support features like icons and tool-tips.
Look and Feel: The plug-gable look and feel lets one design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier to make global changes to your Java programs that provide greater accessibility Look and Feel: AWT components more closely reflect the look and feel of the OS they run on.
Applet Portability: Most Web browsers do not include the Swing classes, so the Java plugin must be use Applet Portability: most Web browsers support AWT classes so AWT applets can run without the Java plugin.
Speed: Comparatively slower

Speed: use of native peers speeds component performance.

Add a comment (3)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 1486

Copy Files from Classpath to another temp location in Java

Here is a snippet to copy a file (just the file name) which is in the classpath to another location

Using all the utility methods provided by java to do so.

 

private void copyReadMeFile
                (String tempFilesOutputPath2, String readmeFile) 
                                              throws IOException {
		
    Path inputPath = Paths.get(this.getClass().getClassLoader().
                              getResource(readmeFile).getPath());
    Path path = Paths.get(tempFilesOutputPath2 + File.separator + readmeFile);
    try {
         Files.copy(inputPath, path, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
         throw e;
    }
}

Add a comment (1)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 3727

How to view complete string variable in the eclipse debugging

When debugging a Java application in eclipse , we often come across a string whose length exceeds the view of the variable display in the eclipse.

Here is an example. (see the ellipses at the end)

 

in order to view the full string , just right click on the variable and click on "Change Value" to view it completely.

 

Add a comment (1)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 4182

Serialization in Java explained with an example program

Here is a shared java project to explain the Serialization/De-serialization.

Just do a git clone of the project using the command below:

 git clone https://github.com/mail2madhva/SerializeExample.git

It has three main classes : MainClass.java is the class which tests the serialization and de-serialization.

Other two classes are the Objects which implement the Serializable interface, so these objects gets serialized.

The serialized data gets stored in the data.bin file on the file system.

The project shows how to serialize an array as well. PersonList stores the list of the Persons in an array list.

 This part of the code in the MainClass.java does the serialization:

String filename = "data.bin";
try {
	ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
	os.writeObject(list);
	os.close();
} catch (FileNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

 The above program is self explanatory , The writeObject() method of ObjectOutputStream is used to serialize the object and which is written to a file using FileOutputStream.

This part of the code does the de-serialization, i.e reads the objects from the file.

try {
	ObjectInputStream is = new ObjectInputStream(new FileInputStream(filename));
        PersonList listRead = (PersonList) is.readObject();
			
	Iterator<Person> it = listRead.getPersonList().iterator();
	
	Person readPerson = null;
	while(it.hasNext()) {
	        readPerson = it.next();
				
		System.out.println("Person  name = " + readPerson.getName() + " age = " + readPerson.getAge() + " email = " + readPerson.getEmail());
				
	}
			
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (ClassNotFoundException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

FileInputStream is used to read the file. ObjectInputStream is created for that file stream. "is.readObject()" reads the Objects from the FileInputStream.

 

Add a comment (1)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 3271

When to use StringBuffer ?

 

StringBuffer is powerful when there are string operations like concatenation/ deletion involved.
Here is a small example to demonstrate the power of StringBuffer.

This program joins the String array into a long String in two possible ways
1) using String + operator
2) using StringBuffer append method.


It also prints out time taken by the methods.

package com.example;

public class Words {

	public static String join(String[] array) {
		long start = System.currentTimeMillis();
		StringBuffer output = new StringBuffer();

		for (String word : array) {
			output.append(word);
		}

		long end = System.currentTimeMillis();
		System.out.println("Time taken = " + (end - start));
		return output.toString();
	}

	public static String join_old(String[] array) {
		long start = System.currentTimeMillis();
		String output = "";

		for (String word : array) {
			output += word;
		}
		long end = System.currentTimeMillis();
		System.out.println("Time taken while using string= " + (end - start));
		return output;
	}

	public static void main(String[] args) {
		String[] test = { "1", "2", "3" };
		System.out.println("Run using Strings");

		join_old(test);
		System.out.println("Run using StringBuffer");

		join(test);
	}
}

Output :

Run using Strings
Time taken while using string= 2
Run using StringBuffer
Time taken = 0

Create a very long test string array to check the differences yourself.

 

Add a comment (1)

  • Written by Madhu V Rao
  • Category: Core Java
  • Hits: 2314
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest