Showing posts with label Files. Show all posts
Showing posts with label Files. Show all posts
Sunday, June 15, 2014
Today in this article I will discuss with an amazing feature of Java7. Here I will show you how to create a file/folder watcher/watch service. In other words I will actually write Java code which will be able to monitor a file/folder/directory for changes. This will require Java 7 NIO .2. This monitoring service is very useful in many applications like IDE. Also this can be used for hot deployment in servers. Monitoring or watching a folder for changes means that whenever there is a change in file system associated with the folder then an event is triggerd. The event is catched and associated change is extracted to know what change has occurred and based on that different actions can be taken.
Below are the steps you must follow to implement watch service
1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.
Below are the steps you must follow to implement watch service
1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.
Labels:Files | 0
comments
Friday, April 4, 2014
Today I will show you how to do 256bits AES encryption and decryption of a file in Java. You can write codes for AES - 128bits without doing any extra configuration but to use AES - 256bits first of all you have to carry out the following steps. This is because when you install JDK it has default strength which is Strong but you will have to increase it to Unlimited.
- Download the right version of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. For JDK7 download it from here
- Extract the archive and copy the two JAR files (local_policy.jar and US_export_policy.jar) and paste it in the directory JAVA_HOME/jre/lib/security for example C:/Program Files/Java/jdk1.7.0/jre/lib/security
In order to perform the encryption, first of all a KeYGenerator instance is created for AES key and the key length is set to 256 using init() method. Then the key is generated which is used for initializing Cipher instance. The generated key is saved to the output file(which will contain encrypted contents) to be used later. The cipher instance is used by the CipherOutputStream to encrypt and write the contents in encrypted format.
In order to decrypt the encrypted file, initially the key that was saved is read from the file. Then that key is used for initializing Cipher for decryption. The cipher instance is used by CipherInputStream to read encrypted contents and generate the original contents which are then written to file using FileOutputStream.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
package com.javaingrab.security.encrypt; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class AESEncryptor { public void encrypt(String fname) throws Exception{ KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); //using AES-256 SecretKey key = keyGen.generateKey(); //generating key Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES aesCipher.init(Cipher.ENCRYPT_MODE, key); //initializing cipher for encryption with key //creating file output stream to write to file try(FileOutputStream fos = new FileOutputStream(fname+".aes")){ //creating object output stream to write objects to file ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(key); //saving key to file for use during decryption //creating file input stream to read contents for encryption try(FileInputStream fis = new FileInputStream(fname)){ //creating cipher output stream to write encrypted contents try(CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)){ int read; byte buf[] = new byte[4096]; while((read = fis.read(buf)) != -1) //reading from file cos.write(buf, 0, read); //encrypting and writing to file } } } } public void decrypt(String fname)throws Exception{ SecretKey key =null; //creating file input stream to read from file try(FileInputStream fis = new FileInputStream(fname)){ //creating object input stream to read objects from file ObjectInputStream ois = new ObjectInputStream(fis); key = (SecretKey)ois.readObject(); //reading key used for encryption Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES aesCipher.init(Cipher.DECRYPT_MODE, key); //initializing cipher for decryption with key //creating file output stream to write back original contents try(FileOutputStream fos = new FileOutputStream(fname+".dec")){ //creating cipher input stream to read encrypted contents try(CipherInputStream cis = new CipherInputStream(fis, aesCipher)){ int read; byte buf[] = new byte[4096]; while((read = cis.read(buf)) != -1) //reading from file fos.write(buf, 0, read); //decrypting and writing to file } } } } public static void main(String[] args) throws Exception { AESEncryptor obj = new AESEncryptor(); obj.encrypt("clear.txt"); obj.decrypt("clear.txt.aes"); } }NOTE : You will need the clear.txt file which is the file to be encrypted to execute the code. The encrypted file will be placed in the same directory with same name as original file but with an extension ".aes". The decrypted file will have the same name as the encrypted file but with extension ".dec", this is done deliverately for you people to check whether the original conetents are same as the decrypted one.
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
Labels:Files,Security | 6
comments
Monday, March 24, 2014
Today I will show you "how to save objects to file" and "how to read objects from file". This is a very important thing which you may need while writing an application in Java. You might have an application where you would like to save the state of an object which you may require later. You can think of using databases, but it is very odd to use it for saving small number of objects. Also it may be that you dont have access to databases. So it is best to use the local file systemand save objects in files. This will make the application more light and have freater performance.
This is very easy to do. Just as you write and read all other things from file, similarly this can be done. You have to do just these two things
This is very easy to do. Just as you write and read all other things from file, similarly this can be done. You have to do just these two things
- The class whose object you want to save must implement the interface java.io.Serializable. This interface is a tagging interface and has no abstract methods. As you knowobjects have existence only in JVM and they have no meaning in the external world. So making a class Serializable is quite like signing a contract with JVM that it can be taken outside it but it will be broken into bytes which will be actually saved in file. Similarly while reading the series of bytes from file will be read and the object will be reconstructed.
- Wgile writing an object you need a stram to write it. The class java.io.ObjectOutputStream will help to write objects while java.io.ObjectInputStream will help to read objects.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Student implements Serializable{ private long roll; private String name; private static final long serialVersionUID = 1L; public Student(long roll, String name){ this.roll = roll; this.name = name; } @Override public String toString() { return "Student [roll=" + roll + ", name=" + name + "]"; } } class SerializableDemo{ public static void main(String[] args) throws ClassNotFoundException, IOException { //creating instance of Student to save to file Student s = new Student(11004L,"Aditya Goyel"); System.out.println("Before saving in file >>\n"+s); //creating the stream to write to file ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("out.dat")); oos.writeObject(s); //writing the object oos.close(); //closing the stream //creating the stream to read from file ObjectInputStream ois = new ObjectInputStream(new FileInputStream("out.dat")); Object o = ois.readObject(); //reading from file if(o instanceof Student) //checking if it is a Student object o = (Student)o; //type-cast to Student System.out.println("\nAfter reading from file >> \n"+o); ois.close(); //closing stream } }-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Before saving in file >>
Student [roll=11004, name=Aditya Goyel]
After reading from file >>
Student [roll=11004, name=Aditya Goyel]
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Labels:Files,Java FAQs | 0
comments
Sunday, March 31, 2013
-------------------------UPDATE-------------------------
I have updated the code on request of some followers so that they can directly use this code for their project without requiring to make any changes.Following changes have been made
- A copy method has been introduced to copy the streams. I reduces unnecessary duplicate codes for copying files.
- Another important update added is that the file decrypted will have the same name it had before encryption along with its extension.
- The last feature added is try with resources. This reduces extra bit of coding to flush and close the streams.
--------------------------------------------------
Today I am going to discuss how you can encrypt any file in Java.For encryption we need a key based on which the encryption will be done. Not only that, I will also show how you can decrypt that file and get back the original one. The encryption algorithm can be chosen by the user. Here we will use some classes Cipher,CipherInputStream,CipherOutputStream,SecretKeySpec. One thing you have to always remember is that the same key must be used both for encryption and decryption. We will use Cipher stream classes as only one function call is required for both either reading/writing and encryption/decryption. Otherwise we would have to call update() method for encryption/decryption and then write() for writing to file.
SecretKeySpec class : This class specifies a secret key in a provider-independent fashion and is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.
Cipher class : This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework. Its getInstance() method is called to get the object based on algorithm. Then the init() method is called for initializing the object with encryption mode and key.
CipherInputStream class : It is composed of an InputStream and a Cipher so that read() methods return data that are read in from the underlying InputStream but have been additionally processed by the Cipher. The Cipher must be fully initialized before being used by a CipherInputStream. It is used for decryption and does read and then update operation.
CipherOutputStream class : Just like above it is also composed of a stream and cipher and the cipher must be fully initialised before using this stream. It is used for encryption purpose.
So below is the code which solves your question how to encrypt a file in Java and also how to decrypt a file. This code actually shows you how to encrypt and decrypt a file using DES or Triple DES in Java.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------The code after update applied
import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.spec.SecretKeySpec; public class FileEncryptor{ private String algo; private String path; public FileEncryptor(String algo,String path) { this.algo = algo; //setting algo this.path = path;//setting file path } public void encrypt() throws Exception{ //generating key byte k[] = "HignDlPs".getBytes(); SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]); //creating and initialising cipher and cipher streams Cipher encrypt = Cipher.getInstance(algo); encrypt.init(Cipher.ENCRYPT_MODE, key); //opening streams FileOutputStream fos =new FileOutputStream(path+".enc"); try(FileInputStream fis =new FileInputStream(path)){ try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){ copy(fis,cout); } } } public void decrypt() throws Exception{ //generating same key byte k[] = "HignDlPs".getBytes(); SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]); //creating and initialising cipher and cipher streams Cipher decrypt = Cipher.getInstance(algo); decrypt.init(Cipher.DECRYPT_MODE, key); //opening streams FileInputStream fis = new FileInputStream(path); try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){ try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){ copy(cin,fos); } } } private void copy(InputStream is,OutputStream os) throws Exception{ byte buf[] = new byte[4096]; //4K buffer set int read = 0; while((read = is.read(buf)) != -1) //reading os.write(buf,0,read); //writing } public static void main (String[] args)throws Exception { new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt(); new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt(); } }The original code before update
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.spec.SecretKeySpec; public class FileEncryptor{ private String algo; private File file; public FileEncryptor(String algo,String path) { this.algo=algo; //setting algo this.file=new File(path); //settong file } public void encrypt() throws Exception{ //opening streams FileInputStream fis =new FileInputStream(file); file=new File(file.getAbsolutePath()+".enc"); FileOutputStream fos =new FileOutputStream(file); //generating key byte k[] = "HignDlPs".getBytes(); SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]); //creating and initialising cipher and cipher streams Cipher encrypt = Cipher.getInstance(algo); encrypt.init(Cipher.ENCRYPT_MODE, key); CipherOutputStream cout=new CipherOutputStream(fos, encrypt); byte[] buf = new byte[1024]; int read; while((read=fis.read(buf))!=-1) //reading data cout.write(buf,0,read); //writing encrypted data //closing streams fis.close(); cout.flush(); cout.close(); } public void decrypt() throws Exception{ //opening streams FileInputStream fis =new FileInputStream(file); file=new File(file.getAbsolutePath()+".dec"); FileOutputStream fos =new FileOutputStream(file); //generating same key byte k[] = "HignDlPs".getBytes(); SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]); //creating and initialising cipher and cipher streams Cipher decrypt = Cipher.getInstance(algo); decrypt.init(Cipher.DECRYPT_MODE, key); CipherInputStream cin=new CipherInputStream(fis, decrypt); byte[] buf = new byte[1024]; int read=0; while((read=cin.read(buf))!=-1) //reading encrypted data fos.write(buf,0,read); //writing decrypted data //closing streams cin.close(); fos.flush(); fos.close(); } public static void main (String[] args)throws Exception { new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt(); new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt(); } }NOTE : The generated decrypted file name is not the same as that of original so that you can check whether same contents have been generated or not. You can change this part.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
DOWNLOAD the complete file encryptor project from Mediafire
NOTE : the project archive contains the java source file, the sample file for encryption and the encrypted file produced after encryption of sample file.
--------------------------------------------------------------------------------------------------------------------------
Related Posts
--------------------------------------------------------------------------------------------------------------------------Search keywords : how to, encrypt, decrypt, files, using DES, for encryption and decryption, java
Happy coding :)
Labels:Files,Security | 32
comments
Sunday, January 13, 2013
Today I am going to post a program that will be able to compress any file in GZIP format. Java language can be used very efficiently for this purpose. There is a special package java.util.zip which contains several classes that can be used for compressing files and folders. Today I am going to deal with GZIPOutputStream . This particular class is used to produce with a file in compressed GZIP format with extension .gz . Here at first the file to be compressed is taken as input from user. Then FileInputStream is used to open a stream connecting to that file. Next the data from file is read in a buffer of capacity 4K. Then the buffer is written to the output stream. Here output stream is nothing but a FileOutputStream wrapped over with a GZIPOutputStream . This process of reading and writing goes on until end of file is reached.
--------------------------------------------------------------------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class CompressFile {
public void gzipFile(String from, String to) throws IOException {
FileInputStream in = new FileInputStream(from); //stream to input file
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to)); //stream to output file
byte[] buffer = new byte[4096]; //defining buffer capacity
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) //reading into buffer
out.write(buffer, 0, bytesRead); //writing buffer contents to output stream
in.close(); //closing both streams
out.close();
}
public static void main(String args[]) throws IOException {
if(args.length>0){
String from=args[0]; //getting source file as command line input
new CompressFile().gzipFile(from,from+".gz");
}
}
}
NOTE : Very soon I will be posting a GUI version of this ptogram.
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class CompressFile {
public void gzipFile(String from, String to) throws IOException {
FileInputStream in = new FileInputStream(from); //stream to input file
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to)); //stream to output file
byte[] buffer = new byte[4096]; //defining buffer capacity
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) //reading into buffer
out.write(buffer, 0, bytesRead); //writing buffer contents to output stream
in.close(); //closing both streams
out.close();
}
public static void main(String args[]) throws IOException {
if(args.length>0){
String from=args[0]; //getting source file as command line input
new CompressFile().gzipFile(from,from+".gz");
}
}
}
NOTE : Very soon I will be posting a GUI version of this ptogram.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Labels:Files,Utils | 1 comments
Tuesday, January 1, 2013
Today I am going to post a program that will be able to display i.e list all the files and folders in your computer. Here we have used the java.io.File class for this purpose. At first we call the listRoots() function to list all the drives. Then for each drive we list all of their contents. A recursive function is defined that takes in a reference of File class instance as parameter. Now if it is a file then its absolute path is displayed. If it is a folder then all the contents of this directory is listed and kept in a File array. Now for each of the elements of the array the recursive function is called. The contents are listed following DFS algorithm.
--------------------------------------------------------------------------------------------------------------------------
import java.io.File;
public class FileList {
static void list(File f){
if (f.isFile()){
System.out.println(f.getAbsolutePath()); //displays path for a file
return;
}
else{
File dir_list[]=f.listFiles(); //lists all contents if a directory
for (File t : dir_list)
try{
list(t); //calls list for each content of directory
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
File drive_list[]=File.listRoots(); //lists all drives
try{
for(File drive : drive_list)
list(drive); //calls recur for each drive
}catch(Exception e){
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.io.File;
public class FileList {
static void list(File f){
if (f.isFile()){
System.out.println(f.getAbsolutePath()); //displays path for a file
return;
}
else{
File dir_list[]=f.listFiles(); //lists all contents if a directory
for (File t : dir_list)
try{
list(t); //calls list for each content of directory
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
File drive_list[]=File.listRoots(); //lists all drives
try{
for(File drive : drive_list)
list(drive); //calls recur for each drive
}catch(Exception e){
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Labels:Files | 0
comments
Subscribe to:
Posts
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...