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

}

No comments:

Post a Comment