Showing posts with label Java I/O. Show all posts
Showing posts with label Java I/O. Show all posts

Monday, 25 April 2016

Can we serialize static variables ?


Serialization
 is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data.

Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation.

There are three exceptions in which serialization does not necessarily read and write to the stream.
 1. Serialization ignores static fields, because they are not part of any particular object's state.
 2. Base class fields are only handled if the base class itself is serializable.
 3. Transient fields.

There are four basic things you must do when you are making a class serializable : 
    1. Implement the Serializable interface.
    2. Make sure that instance-level, locally defined state is serialized properly.
    3. Make sure that superclass state is serialized properly.
    4. Override equals() and hashCode().

It is possible to have control over serialization process ?


It is possible to have control over serialization process ?

The class should implement Externalizable interface.

This interface contains two methods namely readExternal and writeExternal.
You should implement these methods and write the logic for customizing the serialization process.

What are the uses of Serialization ?


Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Uses of Serialization
  • To persist data for future use.
  • To send data to a remote computer using such client / server Java technologies as RMI or socket programming.
  • To "flatten" an object into array of bytes in memory.
  • To exchange data between applets and servlets.
  • To store user session in Web applications .
  • To activate / passivate EJBs.
  • To send objects between the servers in a cluster.

Serializable is a tagging/marker/null interface; it prescribes no methods.

It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence.
ObjectOutputStream serializes only those objects which implement this interface.

How to open local files using Java program ?


Open local files


java.awt.Desktop myNewBrowserDesktop = 
                      java.awt.Desktop.getDesktop();

try {
  // Open local file
  myNewBrowserDesktop.open(new File("C:\\Documents and 
        Settings\\QLDC1776\\Desktop\\notice.pdf"));
} catch (URISyntaxException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

What you can do with Java Zip package ?


java.util.zip provides :
Classes for reading / writing the standard and compressed files or archives in the ZIP and GZIP file formats.

Basically, ZIP file forms for the JAR file format, so it is easier to include classes for manipulating ZIP files as part of the standard Java APIs.
This functionality is very useful, because it saves the time of creating custom file archive formats for your applications.

Classes
GZIPInputStream
implements a stream filter for reading compressed data in the GZIP format

GZIPOutputStream
implements a stream filter for writing compressed data in the GZIP file format

ZipEntry
used to represent a ZIP file entry

ZipFile
used to read entries from a zip file

ZipInputStream
implements an input stream filter for reading files in the ZIP file format


ZipOutputStream
implements an output stream filter for writing files in the ZIP file format

What is the purpose of Externalizable interface ?


The Externizable interface extends Serializable interface.

When you use Serializable interface, your class is serialized automatically by default.
But you can override writeObject() and readObject() two methods to control more complex object serialization process.

When you use Externalizable interface, you have a complete control over your class's serialization process.

The two methods to be implemented are :
  • void readExternal(ObjectInput)
  • void writeExternal(ObjectOutput)

How to redirect standard output stream to a file ?


Use System.setOut

Example
try {
    System.setOut(new PrintStream("src/java.txt"));
    System.out.println("hello");
} catch (FileNotFoundException e1) {
    e1.printStackTrace();

}

How to create and delete files in Java ?


Use createNewFile() and delete() methods

Example
File file = new File("c:\\newfile.txt");
if (file.createNewFile())
  System.out.println("File is created!");
else
  System.out.println("File already exists.");

if(file.delete())
  System.out.println(file.getName() + " is deleted!");
else

  System.out.println("Delete operation is failed.");

How to rename, move or copy files ?


Rename file
File oldfile = new File("oldfile.txt");
File newfile = new File("newfile.txt");
if(oldfile.renameTo(newfile))
  System.out.println("Rename succesful");
else

  System.out.println("Rename failed");


Move file - Rename file but at different location
File afile = new File("C:\\folderA\\Afile.txt");
File bFile = new File("C:\\folderB\\" + afile.getName());
if(afile.renameTo(bFile))
  System.out.println("File is moved successful!");
else
  System.out.println("File is failed to move!");


Copy File
InputStream inStream = null;
OutputStream outStream = null;
try{
  File afile = new File("Afile.txt");
  File bfile = new File("Bfile.txt");
  inStream = new FileInputStream(afile);
  outStream = new FileOutputStream(bfile);

  byte[] buffer = new byte[1024];
  int length;
  //copy the file content in bytes
  while ((length = inStream.read(buffer)) > 0){
     outStream.write(buffer, 0, length);
  }

  inStream.close();
  outStream.close();
  System.out.println("File is copied successful!");
}catch(IOException e){
  e.printStackTrace();

}

How to work on File permissions ?


Check the file permissions
file.canExecute() // Checks if file is executable or not
file.canWrite()   // Checks if file is writable or not
file.canRead()    // Checks if file is readable or not


Set the file permission
file.setExecutable(boolean); // Sets execute permission and return true
file.setReadable(boolean); // Sets read permission and return true

file.setWritable(boolean)// Sets write permission and return true


Check if a file is hidden
File file = new File("c:/hidden-file.txt");
if(file.isHidden())
  System.out.println("This file is hidden");
else

  System.out.println("This file is not hidden");


Making file Read only and Read / Write
File file = new File("c:/MyFile.txt");
// Set the file as read only
file.setReadOnly();
if(file.canWrite())
  System.out.println("This file is writable");
else
  System.out.println("This file is read only");

// Set the file as writable
file.setWritable(true);
if(file.canWrite())
  System.out.println("This file is writable");
else

  System.out.println("This file is read only");

How to get total of free disk space in your partition or volume ?


To get total disk space (in bytes) : getTotalSpace()
To get free disk space including unallocated space (in bytes) : getFreeSpace()
To get free disk space that is usable by user in the VM (in bytes) : getUsableSpace()

Example
File file = new File("c:");

long totalSpace = file.getTotalSpace();
System.out.println("Total size : " + totalSpace + " bytes");
System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");

long usableSpace = file.getUsableSpace();
System.out.println("Space free : " + usableSpace + " bytes");


System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");

long freeSpace = file.getFreeSpace();
System.out.println("Space free : " + freeSpace + " bytes");
System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");