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

No comments:

Post a Comment