Wednesday, January 29, 2014

Reading/Writing Binary Data

Files, such as images, are not made up of characters but of bytes. A byte is a fundamental storage unit in a computer— a number consisting of eight binary digits.

The Java library has a different set of classes, called streams, for working with binary

files.

Here is a simple example of copying binary data from a web site to a file.

You use an InputStream to read binary data.

URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
InputStream in = imageLocation.openStream();

To Write binary data to a file, use FileOutputStream

FileOutputStream out = new FileOutputStream("duke.gif");

The read() method of an input stream reads a single byte and returns –1 when no further input is available. 

The write() method of an output stream writes a single byte.

boolean done = false;
while (!done)
{
             int input = in.read(); // -1 or a byte between 0 and 255
             if (input == -1) 
             { 
                     done = true; 
             }
            else 
            { 
                    out.write(input); 
            }

}

Reading/Writing Text files

In this blog post, you will learn how to read and write files - a very useful skill for processing real world data.

Reading and Writing Text files

Examples of text files include not only files that are created with text editor, such as windows notepad, but also java source files, HTML files, etc.

In Java, the most convenient mechanism for reading text is to use the Scanner class.

To begin, construct a File object with the name of the input file.

File inputFile = new File("input.txt");

Then use the File object to construct a Scanner object.

Scanner in = new Scanner(inputFile);

This Scanner object reads text from the file input.txt.  You can use the Scanner methods (nextInt, nextDouble, next, nextLine) to read data from the input file.

To write output to a file, you construct a PrintWriter object with the desired file name.

PrintWriter out = new PrintWriter("output.txt");
out.println("Hello, World!");
out.printf("Total: %8.2f\n", total);

If the output file already exists, the file is emptied before the new data are written into. If the file doesn't exit, an empty file is created.

When you are done processing a file, be sure to close the Scanner and PrintWriter objects.

in.close();
out.close();

When you specify a file name as a string literal, and the name contains backslash characters (as in a Windows file name), you must supply each backslash twice:
File inputFile = new File("c:\\homework\\input.dat");
Reading Web Pages

You can read the contents of a web page with this sequence of commands:

String address = "http://horstmann.com/index.html";
URL pageLocation = new URL(address);

Scanner in = new Scanner(pageLocation.openStream());


Note: The URL class is contained in the java.net package.

Text Input and Output

Reading Words

The next() method of Scanner class reads the next string that is delimited by white space.

White space includes spaces, tab characters, and the new line characters that separate lines.

The words returned by next() method can contain punctuation marks and other symbols.

Sometimes, you want to read just the words and discard anything that isn’t a letter. You achieve this task by calling the useDelimiter method on your Scanner object:

Scanner in = new Scanner(. . .);
in.useDelimiter("[^A-Za-z]+");

Reading characters

Sometimes, you want to read a file one character at a time. You achieve this task by calling the useDelimiter method on your Scanner object with an empty string:

Scanner in = new Scanner(. . .);
in.useDelimiter("");
char ch = in.next().charAt(0);

Classifying Characters

The Character class declares several methods for this purpose.
Character.isDigit(ch); // returns true if ch is a digit '0....9'

isDigit
isLetter
isUpperCase
isLowerCase
isWhiteSpace - space, new line, tab

Converting Strings to Numbers

If a String contains the digits of a number, you use the Integer.parseInt or Double.parseDouble method to obtain the number value.

String population = "123223432";
int populationValue = Integer.parseInt(population);

The argument must be a string containing the digits of an integer, without any additional characters. Not even spaces are allowed.

In case, if there are any spaces at the end of string, use the trim() method.
int populationValue = Integer.parseInt(population.trim());



Tuesday, January 28, 2014

How to compile to different location

How do I compile to a different location?

By default, execution of the "javac" compiler produces .class files in the same directory where the source code files are located. This location for the generated .class files can be changed using the "-d" switch.

I have a Howdy.java file in my C:\stuff directory. Within the C:\stuff directory is another directory, C:\stuff\bin. I'll compile the Howdy java source file to a class file which will be placed in the bin directory via:


javac -d bin Howdy.java
After compilation, we can see that the Howdy.class file has been created in the bin directory.

Javac will create appropriate directory structure (matching package name hierarchy) starting at destination directory specified.

File I/O - Examples1

Create a File in Java


import java.io.File;
import java.io.IOException;
 
public class CreateFileExample 
{
    public static void main( String[] args )
    { 
     try {
 
       File file = new File("c:\\newfile.txt");
 
       if (file.createNewFile()){
         System.out.println("File is created!");
       }else{
         System.out.println("File already exists.");
       }
 
     } catch (IOException e) {
       e.printStackTrace();
 }
    }
}
Set File Permission in Java

import java.io.File;
import java.io.IOException;
 
public class FilePermissionExample 
{
    public static void main( String[] args )
    { 
     try {
 
       File file = new File("/mkyong/shellscript.sh");
 
       if(file.exists()){
        System.out.println("Is Execute allow: " +file.canExecute());
    System.out.println("Is Write allow : " + file.canWrite());
    System.out.println("Is Read allow : " + file.canRead());
       }
 
       file.setExecutable(false);
       file.setReadable(false);
       file.setWritable(false);
 
       System.out.println("Is Execute allow : " + file.canExecute());
       System.out.println("Is Write allow : " + file.canWrite());
       System.out.println("Is Read allow : " + file.canRead());
 
       if (file.createNewFile()){
         System.out.println("File is created!");
       }else{
         System.out.println("File already exists.");
       }
 
     } catch (IOException e) {
       e.printStackTrace();
     }
    }
}
Get file path of a file in Java

import java.io.File;
import java.io.IOException;
 
public class AbsoluteFilePathExample
{
    public static void main(String[] args)
    { 
     try{
 
         File temp = File.createTempFile("i-am-a-temp-file", ".tmp" );
 
         String absolutePath = temp.getAbsolutePath();
         System.out.println("File path : " + absolutePath);
 
         String filePath = absolutePath.
               substring(0,absolutePath.lastIndexOf(File.separator));
 
         System.out.println("File path : " + filePath);
 
     }catch(IOException e){
 
         e.printStackTrace();
 
     }
 
    }
}
Get Free disk space in Java

import java.io.File;
 
public class DiskSpaceDetail
{
    public static void main(String[] args)
    { 
     File file = new File("c:");
     long totalSpace = file.getTotalSpace(); //total disk space in bytes.
     long usableSpace = file.getUsableSpace(); // available space in bytes.
     long freeSpace = file.getFreeSpace(); //unallocated space in bytes.
 
     System.out.println(" === Partition Detail ===");
 
     System.out.println(" === bytes ===");
     System.out.println("Total size : " + totalSpace + " bytes");
     System.out.println("Space free : " + usableSpace + " bytes");
     System.out.println("Space free : " + freeSpace + " bytes");
 
     System.out.println(" === mega bytes ===");
     System.out.println("Total size : " + totalSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + usableSpace /1024 /1024 + " mb");
     System.out.println("Space free : " + freeSpace /1024 /1024 + " mb");
    }
}
Check if a file Exists

import java.io.*;
 
public class FileChecker {
 
  public static void main(String args[]) {
 
   File f = new File("c:\\mkyong.txt");
 
   if(f.exists()){
    System.out.println("File existed");
   }else{
    System.out.println("File not found!");
   }
 
  }
 
}
Delete a file in Java

import java.io.File;
 
public class DeleteFileExample
{
    public static void main(String[] args)
    { 
     try{
 
      File file = new File("c:\\logfile20100131.log");
 
      if(file.delete()){
       System.out.println(file.getName() + " is deleted!");
      }else{
       System.out.println("Delete operation is failed.");
      }
 
     }catch(Exception e){
 
      e.printStackTrace();
 
     }
 
    }
}
Get file size in Java


import java.io.File;
 
public class FileSizeExample 
{
    public static void main(String[] args)
    { 
  File file =new File("c:\\java_xml_logo.jpg");
 
  if(file.exists()){
 
   double bytes = file.length();
   double kilobytes = (bytes / 1024);
   double megabytes = (kilobytes / 1024);
   double gigabytes = (megabytes / 1024);
   double terabytes = (gigabytes / 1024);
   double petabytes = (terabytes / 1024);
   double exabytes = (petabytes / 1024);
   double zettabytes = (exabytes / 1024);
   double yottabytes = (zettabytes / 1024);
 
   System.out.println("bytes : " + bytes);
   System.out.println("kilobytes : " + kilobytes);
   System.out.println("megabytes : " + megabytes);
   System.out.println("gigabytes : " + gigabytes);
   System.out.println("terabytes : " + terabytes);
   System.out.println("petabytes : " + petabytes);
   System.out.println("exabytes : " + exabytes);
   System.out.println("zettabytes : " + zettabytes);
   System.out.println("yottabytes : " + yottabytes);
  }else{
    System.out.println("File does not exists!");
  }
 
    }
}
Get the number of lines in a file

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
 
public class LineNumberReaderExample 
{
    public static void main(String[] args)
    { 
 
     try{
 
      File file =new File("c:\\ihave10lines.txt");
 
      if(file.exists()){
 
          FileReader fr = new FileReader(file);
          LineNumberReader lnr = new LineNumberReader(fr);
 
          int linenumber = 0;
 
                 while (lnr.readLine() != null){
              linenumber++;
                 }
 
                 System.out.println("Total # of lines : " + linenumber);
 
                 lnr.close();
 
 
      }else{
        System.out.println("File does not exists!");
      }
 
     }catch(IOException e){
      e.printStackTrace();
     }
 
    }
}
List files with certain extension (filter listing of files)

import java.io.File;
import java.io.FilenameFilter;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // create new file
         f = new File("c:/test");
         
         // create new filename filter
         FilenameFilter fileNameFilter = new FilenameFilter() {
   
            @Override
            public boolean accept(File dir, String name) {
               if(name.lastIndexOf('.')>0)
               {
                  // get last index for '.' char
                  int lastIndex = name.lastIndexOf('.');
                  
                  // get extension
                  String str = name.substring(lastIndex);
                  
                  // match path name extension
                  if(str.equals(".txt"))
                  {
                     return true;
                  }
               }
               return false;
            }
         };
         // returns pathnames for files and directory
         paths = f.listFiles(fileNameFilter);
         
         // for each pathname in pathname array
         for(File path:paths)
         {
            // prints file and directory paths
            System.out.println(path);
         }
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}
Rename a file in Java

import java.io.File;
 
public class RenameFileExample 
{
    public static void main(String[] args)
    { 
 
  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");
  }
 
    }
}
Copy a file in Java

Java didn’t comes with any ready make file copy function, you have to manual create the file copy process. To copy file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class CopyFileExample 
{
    public static void main(String[] args)
    { 
 
     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();
     }
    }
}
Move file to a different directory

Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :
  1. File.renameTo().
  2. Copy to new file and delete the original file.
Rename
import java.io.File;
 
public class MoveFileExample 
{
    public static void main(String[] args)
    { 
     try{
 
        File afile =new File("C:\\folderA\\Afile.txt");
 
        if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
      System.out.println("File is moved successful!");
        }else{
      System.out.println("File is failed to move!");
        }
 
     }catch(Exception e){
      e.printStackTrace();
     }
    }
}
Copy and Delete

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class MoveFileExample 
{
    public static void main(String[] args)
    { 
 
     InputStream inStream = null;
 OutputStream outStream = null;
 
     try{
 
         File afile =new File("C:\\folderA\\Afile.txt");
         File bfile =new File("C:\\folderB\\Afile.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();
 
         //delete the original file
         afile.delete();
 
         System.out.println("File is copied successful!");
 
     }catch(IOException e){
         e.printStackTrace();
     }
    }
}
Get file Creation Date in Java

There are no official way to get the file creation date in Java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class GetFileCreationDateExample
{
    public static void main(String[] args)
    { 
 
     try{
 
      Process proc = 
         Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc");
 
      BufferedReader br = 
         new BufferedReader(
            new InputStreamReader(proc.getInputStream()));
 
      String data ="";
 
      //it's quite stupid but work
      for(int i=0; i<6; i++){
       data = br.readLine();
      }
 
      System.out.println("Extracted value : " + data);
 
      //split by space
      StringTokenizer st = new StringTokenizer(data);
      String date = st.nextToken();//Get date
      String time = st.nextToken();//Get time
 
      System.out.println("Creation Date  : " + date);
      System.out.println("Creation Time  : " + time);
 
     }catch(IOException e){
 
      e.printStackTrace();
 
     }
 
    }
}
Get the last modified Date in Java

import java.io.File;
import java.text.SimpleDateFormat;
 
public class GetFileLastModifiedExample
{
    public static void main(String[] args)
    { 
 File file = new File("c:\\logfile.log");
 
 System.out.println("Before Format : " + file.lastModified());
 
 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
 System.out.println("After Format : " + sdf.format(file.lastModified()));
    }
}
Change the last Modified Data for a file in Java

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ChangeFileLastModifiedExample
{
    public static void main(String[] args)
    { 
 
     try{
 
      File file = new File("C:\\logfile.log");
 
      //print the original last modified date
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
      System.out.println("Original Last Modified Date : " 
        + sdf.format(file.lastModified()));
 
      //set this date 
      String newLastModified = "01/31/1998";
 
      //need convert the above date to milliseconds in long value 
      Date newDate = sdf.parse(newLastModified);
      file.setLastModified(newDate.getTime());
 
      //print the latest last modified date
      System.out.println("Lastest Last Modified Date : " 
        + sdf.format(file.lastModified()));
 
     }catch(ParseException e){
 
      e.printStackTrace();
 
     }
 
    }
}
Make a file read only in Java


import java.io.File;
import java.io.IOException;
 
public class FileReadAttribute
{
 
    public static void main(String[] args) throws IOException
    { 
     File file = new File("c:/file.txt");
 
     //mark this file as read only, since jdk 1.2
     file.setReadOnly();
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }
 
     //revert the operation, mark this file as writable, since jdk 1.6
     file.setWritable(true);
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }    
    }
}
How to generate a file checksum in Java

Here is a simple example to demonstrate how to generate a file checksum value with “SHA-1” mechanism in Java.

import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "c:\\INSTLOG.TXT";
 
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
     sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}
Check if a file is hidden in Java

import java.io.File;
import java.io.IOException;
 
public class FileHidden
{
 
    public static void main(String[] args) throws IOException
    { 
     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");
     }
    }
}

Note
The isHidden() method is system dependent, on UNIX platform, a file is considered hidden if it’s name is begins with a “dot” symbol (‘.’); On Microsoft Windows platform, a file is considered to be hidden, if it’s marked as hidden in the file properties.

Creating a temporary file in Java

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

class TempFileDemo
{
   public static void main(String[] args) throws IOException
   {
      System.out.println(System.getProperty("java.io.tmpdir"));
      File temp = File.createTempFile("text", ".txt");
      System.out.println(temp);
      temp.deleteOnExit();
   }
}



List all the files and folders from a directory(not recursive)
  /**
     * List all the files and folders from a directory
     * @param directoryName to be listed
     */
    public void listFilesAndFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            System.out.println(file.getName());
        }
    }

List all the files from a directory
/**
     * List all the files under a directory
     * @param directoryName to be listed
     */
    public void listFiles(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }

List all the folders from a directory (not including recursive sub folders)
/**
     * List all the folder under a directory
     * @param directoryName to be listed
     */
    public void listFolders(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isDirectory()){
                System.out.println(file.getName());
            }
        }
    }

List all files from a directory and sub-directories (recursive)
    /**
     * List all files from a directory and its subdirectories
     * @param directoryName to be listed
     */
    public void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()){
                listFilesAndFilesSubDirectories(file.getAbsolutePath());
            }
        }
    }