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

Wednesday, June 4, 2014

File Read and Write examples in Java

Here is the code of java program to Read text File Line by Line:

http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml

import java.io.*;
class FileRead
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("c:\\textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}


Other way of reading file data:

import java.io.*;
/**
* How To Read File In Java with BufferedReader class
*
*/
public class ReadUsingBufferedReader {
        public static void main(String[] args) 
        {
                System.out.println("Reading File with BufferedReader class");
                //Name of the file
                String fileName="test.text";
                try{
                
                //Create object of FileReader
                FileReader inputFile = new FileReader(fileName);
                
                //Instantiate the BufferedReader Class
                BufferedReader bufferReader = new BufferedReader(inputFile);

                //Variable to hold the one line data
                String line;
                
                // Read file line by line and print on the console
                while ((line = bufferReader.readLine()) != null)   {
                     System.out.println("File Line is: " + line);
                }
                //Close the buffer reader
                bufferReader.close();
                } 
                catch(Exception e){
                    System.out.println("Error in reading file:" + e.getMessage());                  
                }
        }
}
 
Read a specific line: 

import java.io.*;
public class ReadSpecificLine {

        public static void main(String[] args) {
                String line = "";
                int lineNo;
                try {
                        FileReader fr = new FileReader("new.txt");
                        BufferedReader br = new BufferedReader(fr);
                        for (lineNo = 1; lineNo < 10; lineNo++) {
                                if (lineNo == 5) {
                                        line = br.readLine();
                                } else
                                        br.readLine();
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                }
                System.out.println("Line: " + line);
        }
}
 
 

Java read file in memory

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ReadFileInMemory {
        public static void main(String[] args) throws Exception {
             File f = new File("C:/hello.txt");
             long length = f.length();
             MappedByteBuffer buffer = new FileInputStream(f).getChannel().map(
                                FileChannel.MapMode.READ_ONLY, 0, length);
             int i = 0;
             while (i < length) {
                    System.out.print((char) buffer.get(i++));
             }
             System.out.println();
        }
}
 
Reading binary file into byte array in Java 
 
import java.io.*;
public class ReadingBinaryFileIntoByteArray
{
        public static void main(String[] args) 
        {
                System.out.println("Reading binary file into byte array example");
                try{
                        //Instantiate the file object
                        File file = new File("test.zip");
                        //Instantiate the input stread
                        InputStream insputStream = new FileInputStream(file);
                        long length = file.length();
                        byte[] bytes = new byte[(int) length];

                         insputStream.read(bytes);
                         insputStream.close();
        
                         String s = new String(bytes);
                        //Print the byte data into string format
                         System.out.println(s);
                 }
                 catch(Exception e){
                        System.out.println("Error is:" + e.getMessage());
                }
        }
} 

Writing a file using Appending:

import java.io.*;
class WriteToFileWithoutOverwriting {
 public static void main(String args[])
  {
  try{
          FileWriter fstream = new FileWriter("log.txt",true);
          BufferedWriter out = new BufferedWriter(fstream);
          out.write("Line Added on: " + new java.util.Date()+"\n");
          out.close();
    }catch (Exception e){
         System.err.println("Error while writing to file: " +
          e.getMessage());
    }
  }
}
 

Copying Characters from One file to Another file (Copy file):

import java.io.*;

class CopyCharacters {
        public static void main(String[] args) {
           File inFile = new File("input.dat");
           File outFile = new File("output.dat");

           FileReader ins = null;
           FileWriter outs = null;

           try {
                ins = new FileReader(inFile);
                outs = new FileWriter(outFile);

                int ch;
                while((ch = ins.read()) != -1) 
                {
                    outs.write(ch);
                }
            }
            catch(IOException e) {
                   System.out.println(e);
                   System.exit(-1);
            }
            finally {
                   ins.close();
                   outs.close();
            }
       }
  }

Writing Bytes to a file:

import java.io.*;

class WriteBytes {
        public static void main(String[] args) {
           byte cities[] = {'D', 'E', 'L', 'H', 'I', '\n', 'M','A','D','R','S','\n'}
         
           FileOutputStream outfile = null;
 
           try {
                 outfile = new FileOutputStream("city.txt");
                 outfile.write(cities);
                 outfile.close();
           }
           catch(IOException e) {
                  System.out.println(e);
                  System.exit(-1);
           }
     }
 }
 
Reading bytes from file

import java.io.*;

class ReadBytes {
        public static void main(String[] args) {
            FileInputStream infile = null;
            
            int b;
            try {
                  infile = new FileInputStream(args[0]);
                  while ((b = infile.read())!= -1)
                  {
                      System.out.println((char)b);
                  }
                  infile.close(); 
             }
             catch( IOException e)
             {
                  System.out.println(e);
              }
       }
  }
 
 
 

Tuesday, January 28, 2014

File I/O - File class

Applications often interact with the filesystem to output data to and/or input data from files.

Java's standard class library supports filesystem access via its,

  • class File
  • class RandomAccessFile
  • stream
  • writer/reader APIs
Please note that, it’s preferred to access file systems via Java’s New I/O APIs. But you should also know about classic I/O APIs because you’ll encounter them while modifying legacy code that uses classic I/O.

Note: New I/O APIs will be discussed in another blog post.

Reference: http://www.mkyong.com/tutorials/java-io-tutorials/

File

Applications often interact with a filesystem, which is usually expressed as a hierarchy of files and directories starting from a root directory.

Windows and other platforms on which a Java Virtual Machine (JVM) runs typically support at least one filesystem. 

Ex: Unix or Linux platform combines all mounted (attached and prepared) disks into one virtual filesystem.
In contrast, Windows associates a separate filesystem with each active disk drive.

Note: The set of available filesystem roots is affected by various platform-level operations, such as inserting or ejecting removable media, and disconnecting or unmounting physical or virtual disk drives.

Getting filesystem roots

Listing. Dumping available filesystem roots to the standard output device
import java.io.File;

class DumpRoots
{
   public static void main(String[] args)
   {
      
File[] roots = File.listRoots();
      for (File root: roots)
         System.out.println(root);
   }
}

When I run this application on my Windows XP platform, I receive the following output, which reveals four available roots:
A:\
C:\
D:\
E:\
If I ran DumpRoots on a Unix or Linux platform, I would receive one output line consisting of the virtual filesystem root (/).
Getting file instance
Obtain a File instance by calling a File constructor such as File(String pathname), which creates a File instance that stores the pathname string.
File file1 = new File("/x/y"); // on unix or linux platform
File file2 = new File("C:\\temp\\x.dat"); // on windows platform
Note: path is a hierarchy of directories that must be traversed to locate a file or a directory. A pathname is a string representation of a path; a platform-dependent separator character(such as the Windows backslash [\] character) appears between consecutive names.
Caution Always double backslash characters that appear in a string literal, especially when specifying a pathname; otherwise, you run the risk of bugs or compiler error messages.
Each of above example file instances use absolute pathname, which is a pathname that starts with the root directory symbol; no other information is required to locate the file/directory.
  • The java.io package’s classes default to resolving relative pathnames against the current user (also known as working) directory.
  • Default current user working directory is identified by system property user.dir
  • The default name-separator character is from system property file.separator, and is also stored in File's separator and separatorChar class fields.
File offers additional constructors for instantiating this class:
  • File(String parent, String child) creates a new File instance from
    parent pathname string and a child pathname string.
  • File(File parent, String child) creates a new File instance from a parent pathname File instance and a child pathname string.


import java.io.File;
import java.io.IOException;
class FileOperations
{
       public static void main(String[] args) throws IOException
      {
            File file = new File("test.txt");
            file.createNewFile();
            File f1 = file.getAbsoluteFile();
            String str = File.separator;
          
  System.out.println("File separator= "+str);
            System.out.println("File= "+file);
            System.out.println("f1 Absolute File= "+f1.getAbsolutePath());
            System.out.println("Absolute File= "+file.getAbsoluteFile());
            System.out.println("Absolute path = "+file.getAbsolutePath());
            System.out.println("Canonical path = "+file.getCanonicalPath());
            System.out.println("Name = "+file.getName());
            System.out.println("Parent = "+file.getParent());
            System.out.println("Path = "+file.getPath());
            System.out.println("Is absolute = "+file.isAbsolute());
      }
}

Output:
File separator= \
File= test.txt
f1 Absolute File= D:\MyJavaLearning\HelloWorld\test.txt
Absolute File= D:\MyJavaLearning\HelloWorld\test.txt
Absolute path = D:\MyJavaLearning\HelloWorld\test.txt
Canonical path = D:\MyJavaLearning\HelloWorld\test.txt
Name = test.txt
Parent = null
Path = test.txt
Is absolute = false


 
Note Java 6 added long getFreeSpace()long getTotalSpace(), and long getUsableSpace() methods to File that return disk space information about the partition.

File declares five methods that return the names of files and directories located in the directory identified by a File object’s abstract pathname.

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());
            }
        }
    }

Using FilenameFilter to filter listing of files
This following demo example filters all the files based on .txt extension.
import java.io.File;
import java.io.FilenameFilter;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      File[] paths;
      
      try{      
         // new File instance, here we want to list files in directory c:\test
         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();
      }
   }
}
File also declares several methods for creating files and manipulating existing files.

















Creating Temporary File
You can use the overloaded createTempFile() methods to create the temporary file. If you don’t specify a directory in which to store this file, it’s created in the directory identified by the java.io.tmpdir system property.
Listing . Experimenting with temporary files
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();
   }
}
Output:
C:\DOCUME~1\JEFFFR~1\LOCALS~1\Temp\
C:\DOCUME~1\JEFFFR~1\LOCALS~1\Temp\text3436502412322813057.txt

You probably want to remove the temporary file after the user tells the application to save or discard the changes. The deleteOnExit() method lets you register a temporary file for deletion; it’s deleted when the JVM ends without a crash/power loss.
Finally, File implements the java.lang.Comparable interface’s compareTo() method, and overrides equals() and hashCode().