Thursday, August 18, 2016

csv file processing in java


 */
/**/package excel
import java.io.*;
import java.util.StringTokenizer;

public class Cl1 {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

String name;
String roll;
int marks;

File f = new File("C:\\Users\\user\\Documents\\cvv2.csv"); // file path, please change as per your requirements
int ss = size(f);
System.out.println(ss);
String sen[][] = new String [ss][2];
//get the classes ready for file reading

FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new  InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

//-------------------------------------------

String line="";
int index=0;

while((line=br.readLine())!=null){ //read each line
StringTokenizer t = new StringTokenizer(line,","); // split the words
while(t.hasMoreTokens()){
sen[index][0] = t.nextToken();  // store first  word in the zeroth position of the matrix
sen[index++][1] = t.nextToken();// store second word in the first position of the matrix


}

}
//close all the necessary file objects.
fis.close();
   isr.close();
   br.close();
   //modify
   FileWriter fr = new FileWriter(f); // open file writer
   System.out.println("Increment roll numbers by  and store again: ");
   fr.write("Name,Roll\n"); // write the header
   int j=1;
   while(j<ss){
    //sen
    sen[j][1] = Integer.toString(Integer.parseInt(sen[j][1])+5);
    fr.write(sen[j][0]+","+sen[j++][1]+"\n");
   }
   fr.close();
   read(f);
   //modify
 
 
}
static void read(File f) throws IOException{ // function to display file content
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new  InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine())!=null){
System.out.println(line);
}
fis.close();
br.close();
isr.close();

}
static int size(File ff){// function to get the total lines in the file including the header
File f = ff;
int si = 0;
FileInputStream fis;
try {
System.out.println(f);
fis = new FileInputStream(f);
InputStreamReader isr = new  InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line="";

while((br.readLine())!=null){
si++;
}

fis.close();
   isr.close();
   br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("gggg");
e.printStackTrace();
}

return si;
}

}

arraylist with iterator in java


package p1;
import java.io.File;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sujith
 */
public class fileprgm {
 
    public static void main(String[] args) {
        File f1 = new File("e:\\data6.csv");
        try {
            BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(f1)));
            String line;
            List<String> ar = new ArrayList<String>();
            while((line=br.readLine())!=null){
                StringTokenizer st= new StringTokenizer(line,",");
                while(st.hasMoreTokens()){
             
                 
                    ar.add(st.nextToken());
                         
                }
             
            }
         

            Iterator<String> crunchifyIterator = ar.iterator();
while (crunchifyIterator.hasNext()) {

                        if(crunchifyIterator.hasNext()){
                           System.out.print(crunchifyIterator.next()+" ");
                        }
                        if(crunchifyIterator.hasNext()){
                           System.out.print(crunchifyIterator.next()+" ");
                        }
                        if(crunchifyIterator.hasNext()){
                           System.out.print(crunchifyIterator.next()+" ");
                        }

                        System.out.print("\n");
}
        } catch (Exception ex) {
            Logger.getLogger(msuppu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
}

file prgm csv,txt handling

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package p1;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;


public class add_csv {
    public static void main(String[] args) {
        File f1= new File("E://data4.txt");
         BufferedReader br,br2;
         int size=0;
        try {
            br = new BufferedReader(new FileReader(f1));
              String line;
              int sum=0;
            while((line=br.readLine())!=null){
                StringTokenizer st= new StringTokenizer(line,",");
                while(st.hasMoreTokens()){
                    String p=st.nextToken();
                    //sum+=Integer.parseInt(p);
                    System.out.println(p);
                    size++;
                }
   
            }
            br.close();
            br2 = new BufferedReader(new FileReader("E://data4.txt"));
            FileOutputStream os= new FileOutputStream("E://copy4.txt");
            String[] myst= new String[size];
            int i=0;
            while((line=br2.readLine())!=null){
                 StringTokenizer st= new StringTokenizer(line,",");
                  while(st.hasMoreTokens()){
                    String p=st.nextToken();
                    myst[i++]=p;
                      //System.out.println(i);
                }
            }
            System.out.println(" ");
            for(int k=0;k<size;k++){
                for(int j=k+1;j<size;j++){
                    if(myst[k].compareTo(myst[j])>0){
                    String temp=myst[k];
                       // System.out.println("hi");
                    myst[k]=myst[j];
                    myst[j]=temp;
                    }
                }
            }
            for(String pintu:myst){
              System.out.println(pintu);  
              os.write(pintu.getBytes());
              os.write(" \n".getBytes());
            }
            System.out.println("The sum of integer is "+sum);  
        } catch (Exception ex) {
            Logger.getLogger(add_csv.class.getName()).log(Level.SEVERE, null, ex);
        }
         
    }
}

rough work 1 file read and write

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package p1;

import java.io.BufferedReader;
import java.io.File;
import java.io.*;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 *
 * @author sujith
 */
public class str3 {
    public static void main(String[] args){
        File file= new File("C:\\data3.txt");
        File file2=new File("C:\\data3.txt");
       // String[] tokens = null;
        int k=0;
        try{
        //BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            // BufferedReader br= new BufferedReader(new FileReader(f));
            BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            FileInputStream in= new FileInputStream("C:\\data3.txt");
            FileOutputStream op= new FileOutputStream("E:\\data5.txt");
            //InputStreamReader ip=new InputStreamReader(in);          
            //OutputStreamWriter op= new OutputStreamWriter(new FileOutputStream("E:\\data4.txt"));
            //BufferedReader br= new BufferedReader(in);
           // System.out.println(ip);
            while((k=in.read())!=-1){
                System.out.println((char)k);
               // op.write(k);
               // op.append((char)k);
               // System.out.println((byte)k);
              
            }
        String line=null;
        int count=0;
        int i=0;
       
        while((line=br.readLine())!=null){
            //tokens=line.split("\\s+");
            StringTokenizer st= new StringTokenizer(line," ");
          
           while(st.hasMoreTokens()){
               String s=st.nextToken();
               char c;
               StringBuffer sb=new StringBuffer(s);
              for(int j=0;j<sb.length();j++){
                  for(int m=j+1;m<sb.length();m++){
                     // System.out.println(sb.ch);
                      //sb.setCharAt(i, ch);
                      if(sb.charAt(j)>sb.charAt(m)){
                          c=sb.charAt(j);
                          sb.setCharAt(j,sb.charAt(m));
                          sb.setCharAt(m, c);
                      }
                    
                  }
              }
              System.out.println(sb);
               //System.out.println(st.nextToken());             
               //StringBuffer sb=new StringBuffer(st.nextToken());
               // StringBuilder sb= new StringBuilder(st.nextToken());
               //String sb=st.nextToken();
              // String[] sb=new String[]{st.nextToken()};
               //System.out.println(sb.length);
              // System.out.println(st.nextToken());
              
              // op.write(st.nextToken().getBytes());
              // op.write(" ".getBytes());
              
               //System.out.println(st.nextToken().getClass().getName());
             
               op.write(sb.toString().getBytes());
               op.write(" ".getBytes());
           }
            op.write("\n".getBytes());
          
        }
       

        }catch(Exception e){
            System.out.println(e);
        }
    }
   
}

Tuesday, January 12, 2016

write a shell script to check whether given name exists in that file or not.(Assume there is a file “Names” with some strings.)

# search.sh
# Program :         Assume there is a file “Names” with some strings. write a shell
                             script to check whether given name exists in that file or not
# Author :           141740
# Date :              17/03/2015

echo "Enter the name to search"
read name

flg=0
for s in `cat Names`
do
        if [ $s == $name ]
        then
                flg=1
                break
        fi
done

echo
if [ $flg -eq 1 ]
then
        echo "Name is present in the file"
else
        echo "Name is not present in the file"
fi
Output:
 [141740@localhost ~]$ cat Names
chaithra
Supritha
Neenu
Melody

[141740@localhost ~]$ sh search.sh
Enter the name to search
chaithra

Name is present in the file

[141740@localhost ~]$ sh search.sh
Enter the name to search
dsfcx

Name is not present in the file


[141740@localhost ~]$

write a shell script to find maximum and minimum integer in that file or not.(Assume there is a file “Numbers” with some integers)

# minmax.sh
# Program :         Assume there is a file “Numbers” with some integers, write a shell script to find maximum and minimum integer in that file or not. 
# Author :           141740
# Date :              17/03/2015

max=`cut -d ' ' -f1 numbers`
min=`cut -d ' ' -f1 numbers`

for num in `cat numbers`
do
        if [ $num -gt $max ]
        then
                max=$num
        fi
done

for num in `cat numbers`
do
        if [ $num -lt $min ]
        then
                min=$num
        fi
done


echo "The max elements is $max"
echo "The min element is $min"


Output:
[141740@localhost ~]$ cat numbers
10 20 30 40 50
[141740@localhost ~]$ sh minmax.sh
The max elements is 50
The min element is 10

[141740@localhost ~]$












Shell script to display all the files which start from a specific letter? For e.g., if letter = s then all files started with letter s should be displayed from the current directory.

# letter.sh
# Program :         To display all the files which start from a specific letter? For e.g., if letter = s then all files started with letter s should be displayed from the current directory. 
# Author :           sujith
# Date :              17/03/2015

echo "Enter the letter"
read letter

flag=0
len=$(echo "$letter" | wc -c)

if [ $len -eq 2 ]
then
        echo "The names of files starting with $len"
        for str in `ls`
        do
                c=$(echo "$str" | cut -c1)
                if [ $c == $letter ]
                then
                        if [ -f $str ]
                        then
                                flag=1
                                echo $str
                        fi
                fi
        done
        if [ $flag -eq 0 ]
        then
                echo "No files which start with the letter $letter"
        fi
else
        echo "Enter only one letter"
fi


Output:
[141740@localhost ~]$ sh letter.sh
Enter the letter
s
The names of files starting with 2
salary.c
sample
sample.c
samplex.c
search.sh
she116.sh
shel16.sh
shell10.sh
shell11.sh
shell12.sh
shell13.sh
shell1.sh
shell2.sh
shell3.sh
shell4.sh
shell5.sh
shell6.sh
shell7.sh
shell8.sh
shell9.sh
sin.c
sinloop.c
sqaure1.c
sqaure.c
square1.c
square.c
stack.cpp
std.c
strcmp.c
strconcat.c
string.l
strlen.c
strpal.sh
str.sh
structure.cpp
sum.c

[141740@localhost ~]$

[141740@localhost ~]$ sh letter.sh
Enter the letter
z
The names of files starting with 2
No files which start with the letter z


[141740@localhost ~]$

Write a shell script to count number of lines, number of words and number of character in a given file with menu options.

# menu.sh
# Program :         Write a shell script to count number of lines, number of words and number of character in a given file with menu options.
# Author :           sujith
# Date :              17/03/2015

echo "Enter the filename"
read file

echo "menu"
echo "1->lines"
echo "2->words"
echo "3->characters"
echo "4->exit"

echo "Enter the choice"
read choice

case $choice in
        1) set `wc -l $file`
         l=`echo $1`
         echo "no of lines in $file is:$l"
         continue;;
        2) set `wc -w $file`
         w=`echo $l`
         echo "no of words in $file is: $w"
         continue;;
        3) set `wc -c $file`
         c=`echo $l`
         echo "no of characters in $file is : $c"
         continue;;
        4)
        echo "Invalid choice"
        break;
esac


Output:
[141740@localhost ~]$ sh menu.sh
Enter the filename
str.sh
menu
1->lines
2->words
3->characters
4->exit
Enter the choice
1
no of lines in str.sh is:29

[141740@localhost ~]$

[141740@localhost ~]$ sh menu.sh
Enter the filename
str.sh
menu
1->lines
2->words
3->characters
4->exit
Enter the choice
2
no of words in str.sh is:77

[141740@localhost ~]$

[141740@localhost ~]$ sh menu.sh
Enter the filename
str.sh
menu
1->lines
2->words
3->characters
4->exit
Enter the choice
3
no of characters in str.sh is : 357

[141740@localhost ~]$









Shell program to accept a string and display as shown in the following example, suppose str = “RAJESH”

# str.sh
# Program :         To accept a string and display as shown in the following example, suppose str = “RAJESH”
                    





R




R
A



R
A
J


R
A
J
E

R
A
J
E
S
R
A
J
E
S
H

# Author :           sujith
# Date :              17/03/2015

echo "Enter the word to print"
read str

len=$(echo "$str" | wc -c)
a=`expr $len \* 2 - 2`
len=`expr $len - 1`
echo "len=$len"
i=1

while [ $i -le $len ]
do
        b=1
        while [ $b -le $a ]
        do
                echo -n " "
                b=`expr $b + 1`
        done
        a=`expr $a - 2`
        l=1
        while [ $l -le $i ]
        do
                ch=$(echo "$str" | cut -c$l)
                echo -n " $ch"
                l=`expr $l + 1`
        done
        echo " "
        i=`expr $i + 1`
done



Output:
[141740@localhost ~]$ sh str.sh
Enter the word to print
RAJESH
len=6





R




R
A



R
A
J


R
A
J
E

R
A
J
E
S
R
A
J
E
S
H

[141740@localhost ~]$