Sunday, November 16, 2014

File handling in Java





Important classes for file reading:

  FileReader;
  BufferedReader
  FileWriter
  BufferedWriter writer

File file = new File("foo/bar/test.txt");
File parent = file.getParentFile();

if(!parent.exists() && !parent.mkdirs()){
    throw new IllegalStateException("Couldn't create dir: " + parent);


Program from read write file :

Find string in a file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class StringFinder {

public static void main(String[] args)
{
    double count = 0,countBuffer=0,countLine=0;
    String lineNumber = "";
    String filePath = "C:\\Users\\allen\\Desktop\\TestText.txt";
    BufferedReader br;
    String inputSearch = "are";
    String line = "";

    try {
        br = new BufferedReader(new FileReader(filePath));
        try {
            while((line = br.readLine()) != null)
            {
                countLine++;
                //System.out.println(line);
                String[] words = line.split(" ");

                for (String word : words) {
                  if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                  }
                }

                if(countBuffer > 0)
                {
                    countBuffer = 0;
                    lineNumber += countLine + ",";
                }

            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Times found at--"+count);
    System.out.println("Word found at--"+lineNumber);
}
}
import java.io.*;
import java.util.*;

public class Assign6 {

    public static void main(String[] args)     throws FileNotFoundException {

       Scanner console = new Scanner(System.in);
   

       intro();

       

        System.out.print("\tEnter the first file name: ");

                String file1 = console.nextLine();



                System.out.print("\tEnter the second file name: ");

                String file2 = console.nextLine();

                System.out.println();

                System.out.println("Differences Found: \n");

                compareFiles(new Scanner(new File(file1)), (new Scanner(new File(file2))));

    }


Find difference between two files :

    public static void intro() {

        System.out.println("This program reads from two given input files and");

        System.out.println("prints information about the differences between them. \n");

    }

    public static void compareFiles (Scanner file1, Scanner file2) {

        String lineA ;

        String lineB ;

        int x = 1;

        while (file1.hasNextLine() && file2.hasNextLine()) {

            lineA = file1.nextLine();

           lineB = file2.nextLine();

            if (!lineA.equals(lineB)) {

                System.out.println("Line " + x++);

                System.out.println("< " + lineA);

                System.out.println("> " + lineB + "\n");

            }

        }

    }

}

Find matching lines in two files

public int findMatchingLines(java.lang.String file1Name, java.lang.String file2Name) throws java.io.IOException
 {
  Scanner scan1 = new Scanner(new File(file1Name));
  Scanner scan2 = new Scanner(new File(file2Name));
  int i = 1;
 
   while (scan1.hasNext() && scan2.hasNext())
   {
    if(scan1.nextLine().equals(scan2.nextLine()))
    {
    System.out.print(i + " ");
    System.err.println(scan1.nextLine());
    i++;
    }
   }

  return i;
 }
Find a line in file and remove it
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);

C Program to merge alternate lines
/*
 * C Program that Merges Lines Alternatively from 2 Files & Print Result
 */
#include
main()
{
    char file1[10], file2[10];

    puts("enter the name of file 1");      /*getting the names of file to be concatenated*/
    scanf("%s", file1);
    puts("enter the name of file 2");
    scanf("%s", file2);
    FILE *fptr1, *fptr2, *fptr3;
    fptr1=fopen(file1, "r");             /*opening the files in read only mode*/
    fptr2=fopen(file2, "r");
    fptr3=fopen("merge2.txt", "w+");   /*opening a new file in write,update mode*/
    char str1[200];
    char ch1, ch2;
    int n = 0, w = 0;
    while (((ch1=fgetc(fptr1)) != EOF) && ((ch2 = fgetc(fptr2)) != EOF))
    {
        if (ch1 != EOF)             /*getting lines in alternately from two files*/
        {
            ungetc(ch1, fptr1);
            fgets(str1, 199, fptr1);
            fputs(str1, fptr3);
            if (str1[0] != 'n')
                n++;      /*counting no. of lines*/
        }
        if (ch2 != EOF)
        {
            ungetc(ch2, fptr2);
            fgets(str1, 199, fptr2);
            fputs(str1, fptr3);
            if (str1[0] != 'n')
                n++;        /*counting no.of lines*/
        }
    }
    rewind(fptr3);
    while ((ch1 = fgetc(fptr3)) != EOF)       /*countig no.of words*/
    {
        ungetc(ch1, fptr3);
        fscanf(fptr3, "%s", str1);
        if (str1[0] != ' ' || str1[0] != 'n')
            w++;
    }
    fprintf(fptr3, "\n\n number of lines = %d n number of words is = %d\n", n, w - 1);
    /*appendig comments in the concatenated file*/
    fclose(fptr1);
    fclose(fptr2);
    fclose
Replace a line or word in File
Replace a line or word in a file

import java.io.*;

public class BTest
    {
     public static void main(String args[])
         {
         try
             {
             File file = new File("file.txt");
             BufferedReader reader = new BufferedReader(new FileReader(file));
             String line = "", oldtext = "";
             while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
             }
             reader.close();
             // replace a word in a file
             //String newtext = oldtext.replaceAll("drink", "Love");
           
             //To replace a line in a file
             String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
           
             FileWriter writer = new FileWriter("file.txt");
             writer.write(newtext);writer.close();
         }
         catch (IOException ioe)
             {
             ioe.printStackTrace();
         }
     }
}

Append content to a file in java
package com.mkyong.file;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample
{
    public static void main( String[] args )
    {
     try{
      String data = " This content will append to the end of the file";

      File file =new File("javaio-appendfile.txt");

      //if file doesnt exists, then create it
      if(!file.exists()){
       file.createNewFile();
      }

      //true = append file
      FileWriter fileWritter = new FileWriter(file.getName(),true);
             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
             bufferWritter.write(data);
             bufferWritter.close();

         System.out.println("Done");

     }catch(IOException e){
      e.printStackTrace();
     }
    }
}
List files in directory
import java.io.*;

class Main {
   public static void main(String[] args) {
      File dir = new File("F:");
      File[] files = dir.listFiles();
      FileFilter fileFilter = new FileFilter() {
         public boolean accept(File file) {
            return file.isDirectory();
         }
      };
      files = dir.listFiles(fileFilter);
      System.out.println(files.length);
      if (files.length == 0) {
         System.out.println("Either dir does not exist
         or is not a directory");
      }
      else {
         for (int i=0; i< files.length; i++) {
            File filename = files[i];
            System.out.println(filename.toString());
         }
      }
   }
}

read file and reverse it

import java.io.*;
    import java.utili.*;

        public class ReverseFile
         {
         public static void main(String[] args) throws IOException
          {
      try{
      File sourceFile=new File(args[0]);
      Scanner content=new Scanner(sourceFile);
      PrintWriter pwriter =new PrintWriter(args[1]);

      while(content.hasNextLine())
      {
         String s=content.nextLine();
         StringBuffer buffer = new StringBuffer(s);
         buffer=buffer.reverse();
         String rs=buffer.toString();
         pwriter.println(rs);
      }
      content.close();  
      pwriter.close();
      System.out.println("File is copied successful!");
      }

      catch(Exception e){
          System.out.println("Something went wrong");
      }
   }
      }

join-lines-2-files-and-store-in-new-file


http://www.sanfoundry.com/c-program-join-lines-2-files-and-store-in-new-file/

No comments:

Post a Comment