在java中读取streamfile

时间:2015-05-14 05:05:19

标签: java file csv filestream filereader

我正在使用逗号分隔值file.i想要从每个原始数据中提取第一个位置[数组中的“0”位置],并希望对其进行一些数学计算。

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

获得第一个位置它会给我这样的错误

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

它适用于第二和第三位置,但对于第四位,它会产生与第一位相同的错误。

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

    }
}              

这里仅举例来说我提取了值[1](表示数组中的第二个位置,如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

这个代码适用于值[1]和值[2]而不是值[0]和值[3] ..为什么我不能理解请帮助我......

4 个答案:

答案 0 :(得分:1)

当您阅读该行时,它显然会返回周围的引号,如下所示:

"12,32,45,76"

因此,当您拆分它时,您将获得以下元素:

"12
32
45
76"

正如您所看到的那样,行中的第一个和最后一个元素不是数字,因此 Double.ParseDouble(..)调用失败。

您应该修改原始字符串(通过子字符串或更优选地使用 .reaplce(“\”“,”“))或者在拆分后检查每个元素然后替换/修剪引号。

答案 1 :(得分:0)

bacause values [1]和value [2]有引号,你应该String.replaceAll()引号。

答案 2 :(得分:0)

我可以注意到各种问题:

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

为什么要两次声明并实例化inputStream

你打算用这个做什么:

        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]); 
        first=first+2;
        String data1 = inputStreamm.next();   //read each line and store in data
        String[] values1 = data1.split(",");  
        //inputStream.next();          
        double second = Double.parseDouble(values1[1]); 
        second=second+1;

它重复了我的味道。

编辑:我很快就完成了一个能为你完成工作的程序:

public static void main(String[] args) {
        String csvFile = "src/files/text/simple.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        boolean readingHeader = true;
        String integerValues = "";
        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {
                // use comma as separator
                if(readingHeader) {
                    readingHeader = false;
                    continue;
                }
                String[] values = line.split(cvsSplitBy); // we get ints here.
                integerValues = integerValues + values[0] + ",";
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(integerValues);

    }

打印:12,23,32,73,73,。你需要做一些清理,但它会给你一个想法。

答案 3 :(得分:0)

在生成异常和可读性方面,您的代码存在一些问题。

我重写了你的代码并且它正在运行:

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输入文件:

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输出文件:

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

完成的更改是:

  
      
  1. inputStreamm.next();
  2. 替换inputStreamm.nextLine();   
  3. 代码重构。首先处理values,然后values1
  4.   
  5. 添加了if (inputStreamm.hasNext())来处理NoSuchElementException
  6.   
  7. Double.parseDouble(values1[1]);替换为Integer.parseInt(values1[1]);,因为它正在生成34.0,您希望输出文件中显示34
  8.