Search code examples
javafilecsvfilestreamfilereader

Read streamfile in java


I am working on comma separated value file.i want to extract first position["0" place in array] value from each raw and want to some math calculation on it.

csv inputfile is like this
a,b,c,d
12,32,45,76
23,45,77,56
32,34,49,28
73,92,26,68
73,36,77,26

for getting first position it give me error like this

Exception in thread "main" java.lang.NumberFormatException: For input string: ""12"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1268)

at java.lang.Double.parseDouble(Double.java:548)
    at rotation.pkg45.Rotation45.main(Rotation45.java:49)//code line no-49

it work fine for second and third position but for the fourth it give the same error as first.

 package rotation.pkg45;import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
public class Rotation45 {
 public static void main(String[] args)throws IOException {
        String filename = "bank-full2.csv";
        ArrayList<String> namesList = new ArrayList<String>( );
        String[] t1;
       // StringBuilder sb;
        List<Double> list = new ArrayList<Double>();
        File file = new File(filename);
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter("bank2test1.csv"));     
               double a1=0.866025;
        double a2=0.5;
        double a3=-0.5;
        double a4=0.866025;
        double b1;
        double b2;
        double c1;
        double c2;          

            Scanner inputStream = new Scanner(file);
            inputStream.next();  
             Scanner inputStreamm = new Scanner(file);
            inputStreamm.next();          

         while (inputStreamm.hasNext()) {   //while loop for find MEAN
            String data = inputStreamm.next();   //read each line and store in data
            String[] values = data.split(",");  //every line splited with " ; " and store each attribute in string list 

            double first = Double.parseDouble(values[1]); 


          /* no suchelementexeption  */  String data1 = inputStreamm.next();   //read each line and store in data
            String[] values1 = data1.split(",");  
            //inputStream.next();          
            double second = Double.parseDouble(values1[1]); 

            c1= ((a2*second)+(a1*first));
    c2= ((a3*first)+(a4*second));
       values1[2] = String.valueOf(c2);
        values[2] = String.valueOf(c1);
       StringBuilder sb = new StringBuilder();
            //  String newData = sb.toString();
            for (int i = 0; i<values.length ; i++) {
                    sb.append(values[i]);
                    if (i < values.length - 1) {
                    sb.append(",");
                }
                    }
             sb.append("\n");
              for (int i = 0; i<values1.length ; i++) {
                    sb.append(values1[i]);
                    if (i < values.length - 1) {
                    sb.append(",");
                }
                    }
            // get the new string
           // System.out.println(sb.toString());

            writer.write(sb.toString()+"\n");
                }
            writer.close();

            inputStreamm.close();


            }
        catch (FileNotFoundException ex)
              {
            Logger.getLogger(Rotation45.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}              

here just for example i had extracted values[1](means second position in array like 32,45,34,..)

so result will be..
12,34,45,76
23,46,77,56
32,36,49,28
73,93,26,68
73,38,77,26

this codeis works for values[1]and value[2] not in values[0]and value[3]..why i cant understand pls help me...


Solution

  • There were some problem in your code in terms of generating exception and readability.

    I rewrote your code and it is working :

    package rotation.pkg45;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Rotation45 {
        public static void main(String[] args) throws IOException {
            String filename = "bank-full2.csv";
            File file = new File(filename);
            BufferedWriter writer = null;
    
            try {
                writer = new BufferedWriter(new FileWriter("bank2test1.csv"));
    
                Scanner inputStreamm = new Scanner(file);
                inputStreamm.nextLine();
    
                while (inputStreamm.hasNext()) { // while loop for find MEAN
                    String data = inputStreamm.nextLine(); // read each line and store in data
                    String[] values = data.split(","); // every line splited with " , " and store each attribute in string list
    
                    // double value is generating 34.0 value, and you are expecting only 34
                    // double first = Double.parseDouble(values[1]);
                    int first = Integer.parseInt(values[1]);
                    first = first + 2;
    
                    values[1] = String.valueOf(first);
                    StringBuilder sb = new StringBuilder();
                    // String newData = sb.toString();
                    for (int i = 0; i < values.length; i++) {
                        sb.append(values[i]);
                        if (i < values.length - 1) {
                            sb.append(",");
                        }
                    }
    
                    if (inputStreamm.hasNext()) { /* To handle NoSuchElementException */
                        String data1 = inputStreamm.nextLine(); // read each line and store in data
                        String[] values1 = data1.split(",");
    
                        // double second = Double.parseDouble(values1[1]);
                        int second = Integer.parseInt(values1[1]);
                        second = second + 1;
                        values1[1] = String.valueOf(second);
    
                        sb.append("\n");
                        for (int i = 0; i < values1.length; i++) {
                            sb.append(values1[i]);
                            if (i < values.length - 1) {
                                sb.append(",");
                            }
                        }
                    }
                    writer.write(sb.toString() + "\n");
                }
                writer.close();
    
                inputStreamm.close();
    
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Rotation45.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

    CSV input file:

    a,b,c,d
    12,32,45,76
    23,45,77,56
    32,34,49,28
    73,92,26,68
    73,36,77,26
    

    CSV output file:

    12,34,45,76
    23,46,77,56
    32,36,49,28
    73,93,26,68
    73,38,77,26
    

    Changes done are:

    1. Replaced inputStreamm.next(); with inputStreamm.nextLine();
    2. Code refactored. Processing of values is done first and then values1.
    3. Added if (inputStreamm.hasNext()) to handle NoSuchElementException.
    4. Replaced Double.parseDouble(values1[1]); with Integer.parseInt(values1[1]);, as it was generating 34.0 and you wanted 34 in your output file.