【问题标题】:read csv data with space and fetching it into array by using java使用空间读取csv数据并使用java将其提取到数组中
【发布时间】:2014-06-11 22:37:21
【问题描述】:
  1. 我正在使用java程序读取csv文件(成功完成)

  2. 我想提取二维数组中的所有数据(部分成功)

我面临的问题是,当某些单词有空格(例如“洛杉矶”、“新德里”)时,它会显示错误 -

我的employee.CSV 文件就像-

姓名、年龄、城市、国家、工资

约翰,25,洛杉矶,美国,30000

大卫,28,巴黎,法国,45000

李安妮,23,东京,日本,20000

Hemal,24,新德里,印度,40000

如果没有空格,例如。 LosAngeles , NewDelhi ,然后它对我来说工作正常,但我需要只有空间的数据。(我想在 selenium 中使用填充数组)

我写的代码如下-

package java2package;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Datadriven {
public static void main(String[] args) {
String[][] myArray = new String[4][5];

    String[] tempArray=new String[5];
    int Rowc=0;
    String fileName="employee.csv";
    File file=new File(fileName);
try 
{

    Scanner content=new Scanner(file);
    content.next();
    while(content.hasNext())
    {
        String data=content.next();
        tempArray=data.split(",");

        for(int i=0;i<5;i++)
        {   
            myArray[Rowc][i]=tempArray[i];

        }

        Rowc++;
    }
    content.close();
    for(int i=0;i<4;i++){
    for(int j=0;j<5;j++){
    System.out.print(myArray[i][j]+" ");
    }
    System.out.print("\n");
    }

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


    }

}

我正在使用 Eclipse,我得到的错误是 - 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at java2package.Datadriven.main(Datadriven.java:31)

【问题讨论】:

  • 而错误是.....?
  • 参考这个question
  • 我正在使用 Eclipse,我得到的错误是 - 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at java2package.Datadriven.main(Datadriven.java:31)
  • 友好的程序点。最好将错误和堆栈跟踪添加到实际问题本身,而不是在评论部分。
  • @Thalesh 您是说要将 csv 文件中的所有数据放入二维数组中,包括带空格的数据?

标签: java arrays csv


【解决方案1】:

通过使用next(),您只会阅读到下一个空白字符。由于您正在对数组长度进行硬编码,因此您会得到一个 ArrayIndexOutOfBoundsException,因为您最终得到的元素比您预期的要少。

使用hasNextLine()nextLine() 应该会产生您想要的结果。但无论如何,检查边界可能是个好主意,因为您使用的是外部数据。

【讨论】:

  • 没错,我一直在寻找这样的解释,它可以指导我在哪里犯错,我是 java 新手,但我试图用你的替换我的代码行 while(content.hasNext( )) >>> while(content.hasNextLine()) ###### String data=content.nextLine() 但不幸的是它对我不起作用,即使我会说它在没有可用空间时不起作用Employee.csv 文件(意味着如果将 csv 文件“LosAngeles”、“NewDelhi”分别放在“Los Angeles”、“New Delhi”的位置,则不起作用
  • 你现在有什么问题?
  • 您修改后的代码出现的错误是 - 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 at java2package.Datadriven.main(Datadriven.java:31)
  • 遇到异常时Rowc 的值是多少?也许您在文件的某处有一个额外的空白行。就像我之前提到的,如果您不确定文件的格式,那么硬编码索引不是一个好主意。
【解决方案2】:

您可以尝试使用 IO 缓冲区来读取数据,而不是扫描仪。下面的示例使用 MappedByteBuffer 遍历 csv 文件并将数据检索到数组中。

public class SO {
public static void main(String[] args) {
    String[][] myArray = new String[4][5]; //Your array
    Path file = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.csv"); //Path to file
    try {
        RandomAccessFile raf = new RandomAccessFile(file.toString(), "rw"); //Get file
        MappedByteBuffer mbuff = raf.getChannel().map(MapMode.READ_WRITE, 0L, Files.size(file)); //Create mapped buffer to file for bytes transfer

        mbuff.position(28); //  //Name,Age,City,Country,Salary = 28 bytes, so we will position buffer after start headings
        for(int i = 0; i < 4; i++){//For each array
            for(int j = 0; j < 5; j++){//For each element
                myArray[i][j] = getSegment(mbuff); //Get the next 'segment' which should be desired value
                System.out.print("\"" + myArray[i][j] + "\"" + " ");//Print array as proof of what it contains
            }
            System.out.println();
        }

    raf.close();
    } catch (IOException io) {
        io.printStackTrace();
    }
}

public static String getSegment(MappedByteBuffer mb){
    StringBuilder sb = new StringBuilder();//StringBuilder to hold segment
    while(mb.hasRemaining()){
        char c = (char)mb.get();//Each individual char
        if((c == '\n' || c == '\r') && sb.length() == 0){//Ignore newline unless their is value is Stringbuilder
            continue;
        } else if((c == '\n' || c == '\r')){//Newline and something is in the Stringbuilder
                break;//Break loop to return the 'segment'
        } else if(c != ','){ //Not a comma
            sb.append(c); //Append
        } else if(mb.position() == mb.capacity()){ //End of file
            break; //Break loop
        } else {
            break; //Break
        }
    }
    return sb.toString();//Return segment
}
}

祝你好运!

【讨论】:

    【解决方案3】:

    更好的是,使用 csv 库,例如 opencsv,示例如下:

    CSV csv = CSV
        .separator(',')  // delimiter of fields
        .quote('"')      // quote character
        .create();       // new instance is immutable
    csv.read("employee.CSV", new CSVReadProc() {
        public void procRow(int rowIndex, String... values) {
            System.out.println(rowIndex + ": " + Arrays.asList(values));
        }
    });
    

    如果您还有其他问题,请随时发表评论...

    【讨论】:

      【解决方案4】:

      这是最简单的没有缺陷的模板,它还需要注意您的 CSV 是否将第一行作为标题。好的是它,如果你交换标题就不会失败。

      最终这将返回一个Model 的数组。如果您愿意,您可以转换成二维字符串数组。 :)

      看看这是否有帮助:

      public class ReadCSV {
      
      public static final String NAME = "Name";
      public static final String AGE = "Age";
      public static final String CITY = "City";
      public static final String COUNTRY = "Country";
      public static final String SALARY = "Salary";
      public static String[] headers;
      
      public static Model[] readData(String fileName) {
          BufferedReader reader = null;
          String line = null;
          List<Model> models = new ArrayList<Model>();
          String[] split = null;
          int index = 0;
          try {
              reader = new BufferedReader(new FileReader(fileName));
              while ((line = reader.readLine()) != null) {
                  split = line.split(",");
                  if (split != null && split.length > 0) {
                      if (index > 0)
                          models.add(getModel(split));
                      else {
                          headers = new String[split.length];
                          System.arraycopy(split, 0, headers, 0, split.length);
                      }
                  }
                  index++;
              }
      
          }
          catch (FileNotFoundException e) {
          }
          catch (Exception e) {
          }
          finally {
              try {
                  reader.close();
              }
              catch (Exception e) {
              }
          }
      
          return models.toArray(new Model[0]);
      
      }
      
      private static Model getModel(String[] split) {
          Model model = new Model();
      
          for (int i = 0; i < headers.length; i++) {
              try {
                  if (headers[i] != null && headers[i].equalsIgnoreCase(NAME)) {
                      model.setName(split[i]);
      
                  }
                  else if (headers[i] != null && headers[i].equalsIgnoreCase(COUNTRY)) {
                      model.setCountry(split[i]);
      
                  }
                  else if (headers[i] != null && headers[i].equalsIgnoreCase(CITY)) {
                      model.setCity(split[i]);
      
                  }
                  else if (headers[i] != null && headers[i].equalsIgnoreCase(AGE)) {
                      model.setAge(convertInt(split[i]));
      
                  }
                  else if (headers[i] != null && headers[i].equalsIgnoreCase(SALARY)) {
                      model.setSalary(convertDouble(split[i]));
      
                  }
                  else {
      
                  }
              }
      
              catch (Exception e) {
              }
          }
      
          return model;
      }
      
      private static double convertDouble(String s) {
          double value = 0.0;
          try {
              value = Double.parseDouble(s);
          }
          catch (Exception e) {
          }
          return value;
      }
      
      private static int convertInt(String s) {
          int value = 0;
          try {
              value = Integer.parseInt(s);
          }
          catch (Exception e) {
          }
          return value;
      }
      
      }
      
      class Model {
      private String name;
      private int age;
      private String city;
      private String country;
      private double salary;
      
      public String getName() {
          return name;
      }
      
      public void setName(String name) {
          this.name = name;
      }
      
      public int getAge() {
          return age;
      }
      
      public void setAge(int age) {
          this.age = age;
      }
      
      public String getCity() {
          return city;
      }
      
      public void setCity(String city) {
          this.city = city;
      }
      
      public String getCountry() {
          return country;
      }
      
      public void setCountry(String country) {
          this.country = country;
      }
      
      public double getSalary() {
          return salary;
      }
      
      public void setSalary(double salary) {
          this.salary = salary;
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        • 2020-08-01
        • 1970-01-01
        • 2021-05-25
        • 2016-11-04
        相关资源
        最近更新 更多