Java 将cvs文件中的多个值放入数组中

Java 将cvs文件中的多个值放入数组中,java,arrays,csv,Java,Arrays,Csv,值以逗号分隔,格式如下: Country,Timescale,Vendor,Units Africa,2010 Q3,Fujitsu Siemens,2924.742632 我想为每个值创建一个数组。我怎么做 我尝试了很多东西,代码如下: BufferedReader br = null; String line = ""; String cvsSplitBy = ","; try { br = new BufferedReader(new FileReader(csvFile));

值以逗号分隔,格式如下:

Country,Timescale,Vendor,Units
Africa,2010 Q3,Fujitsu Siemens,2924.742632
我想为每个值创建一个数组。我怎么做

我尝试了很多东西,代码如下:

BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {

    br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {
        String[] country = line.split(cvsSplitBy);
        country[0] +=",";
        String[] Krajina = country[0].split(",");
使用I/O时始终尝试使用

以下代码应该可以帮助您:

String line = "";
String cvsSplitBy = ",";
List<String> countries = new ArrayList<>();
List<String> timeScales = new ArrayList<>();
List<String> vendors = new ArrayList<>();
List<String> units = new ArrayList<>();

//use try-with resources
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
  while ((line = br.readLine()) != null) {

    String[] parts = line.split(cvsSplitBy);
    countries.add(parts[0]);
    timeScales.add(parts[1]);
    vendors.add(parts[2]);
    units.add(parts[3]);
  }

}
catch (FileNotFoundException e) {
  e.printStackTrace();
}
catch (IOException e) {
  e.printStackTrace();
}

for (String country: countries) {
  System.out.println(country);
}

for (String scale: timeScales) {
  System.out.println(scale);
}

for (String vendor: vendors) {
  System.out.println(vendor);
}

for (String unit: units) {
  System.out.println(unit);
}
字符串行=”;
字符串cvsSplitBy=“,”;
列表国家=新的ArrayList();
List timeScales=new ArrayList();
列出供应商=新的ArrayList();
列表单位=新的ArrayList();
//使用try和资源
try(BufferedReader br=new BufferedReader(new FileReader(csvFile))){
而((line=br.readLine())!=null){
字符串[]部分=行分割(cvsSplitBy);
添加(第[0]部分);
时间尺度。添加(第[1]部分);
供应商。添加(第[2]部分);
单位.添加(零件[3]);
}
}
catch(filenotfounde异常){
e、 printStackTrace();
}
捕获(IOE异常){
e、 printStackTrace();
}
for(字符串国家:国家){
System.out.println(国家);
}
用于(字符串比例:时间刻度){
系统输出打印项次(比例);
}
用于(字符串供应商:供应商){
系统输出打印项次(供应商);
}
用于(字符串单位:单位){
系统输出打印项次(单位);
}

在处理文件之前,您必须定义数组:

String[] country = new String[30];
String[] timescale = new String[30];
String[] vendor = new String[30];
String[] units = new String[30];
在读取行时,您必须将值放在具有相同索引的已定义数组中,为了保持索引,请使用另一个变量,并在每次迭代时增加它。应该是这样的:

int index = 0;

while (true) {
    if (!((line = br.readLine()) != null)) break;
    String[] splitted = line.split(",");
    country[index] = splitted[0];
    timescale[index] = splitted[1];
    vendor[index] = splitted[2];
    units[index] = splitted[3];
    index++;
} 
/// Fill the Arrays with data.
fillDataArrays("DataFile.txt", true);

// Display the filled Arrays.
System.out.println(Arrays.toString(country));
System.out.println(Arrays.toString(timeScale));
System.out.println(Arrays.toString(vendor));
System.out.println(Arrays.toString(units));

由于您的csv可能会包含标题,您可能还想跳过第一行。

您似乎在谈论的是利用另一种称为并行阵列的方法,在这个特定的用例中,这通常是一个坏主意,因为以后可能会出现边界外异常。更好的解决方案是利用二维(2D)数组或ArrayList。尽管如此,并行阵列仍然是:

你说数组大小为30,也许今天是,但明天可能是25或40,因此为了调整数组大小以容纳文件数据,你需要知道CSV文件中包含了多少行实际的原始数据(不包括标题、可能的注释和可能的空行)。最简单的方法是将所有内容转储到单独的ArrayList中,然后稍后将它们转换为各自的数组,比如String、int、long、double等等

首先计数文件行以便初始化数组:

一行代码可以提供所提供文本文件中包含的行数:

long count = Files.lines(Paths.get("C:\\MyDataFiles\\DataFile.csv")).count();
然而,实际上,如果出现IO异常,上述代码行本身确实需要包含在try/catch块中,因此代码比一行多一点。对于CSV文件包含标题行且没有注释或空行的简单用例,这可能是您所需要的,因为您所需要做的只是从初始化阵列的总计数中减去一以消除标题行。上述一个线性函数的另一个小问题是,它在长整数(长)数据类型中提供了一个计数值。这是不好的,因为Java数组在初始化时只接受整数(int)值,因此需要将获得的值转换为整数,例如:

String[] countries = new String[(int) count];
只有当计数不超过整数MAX_值
-2(2147483645)时,这才是好的。这是很多数组元素,所以一般来说,你不会有这个问题,但是如果处理非常大的数组初始化,那么你也需要考虑<强> jvm < /强>内存并用完。 有时,当从CSV(或其他)文本文件获取原始数据行的总数时,有一种可以用于多种不同情况的方法是很好的。下面提供的方法显然不仅仅是一行代码,但它确实为计算文件中的内容提供了更大的灵活性。如前所述,可能会出现标题行。头行在CSV文件中非常常见,通常是文件中的第一行,但情况并非总是如此。标题行前面可以有注释行,甚至可以是空行。但是,标题行应始终是原始数据行之前的第一行。以下是一个可能的CSV文件示例:

示例CSV文件内容:

前两行是注释行,注释行始终以哈希(#)字符或分号(;)开头。这些行在读取时将被忽略

第三行是一个空白行,除了美学之外,没有任何其他用途(我想眼睛更容易看)。这些行也可以忽略

原始数据行正上方的第四行是标题行。该行可能包含在CSV文件中,也可能不包含在CSV文件中。其目的是为每个原始数据行中包含的数据记录提供列名。可以读取此行(如果存在)以获取记录字段(列)名称

CSV文件中的其余行是原始数据行,否则会被视为数据记录。每一行都是一个完整的记录,该记录的每个分隔元素都被视为一个数据字段值。这些是要计数的行,以便初始化不同的数组。以下是一种允许您执行此操作的方法:

FileLineScont()方法:

然后,为了填充这些数组,我们将使用如下方法:

int index = 0;

while (true) {
    if (!((line = br.readLine()) != null)) break;
    String[] splitted = line.split(",");
    country[index] = splitted[0];
    timescale[index] = splitted[1];
    vendor[index] = splitted[2];
    units[index] = splitted[3];
    index++;
} 
/// Fill the Arrays with data.
fillDataArrays("DataFile.txt", true);

// Display the filled Arrays.
System.out.println(Arrays.toString(country));
System.out.println(Arrays.toString(timeScale));
System.out.println(Arrays.toString(vendor));
System.out.println(Arrays.toString(units));

对于“cvs”文件,我们是否可以假设您指的是“CSV”文件,即逗号分隔的值文件?您所说的“为每个值生成数组”是什么意思?例如,如果您有2行输入,您希望结果是什么,即您希望最终得到什么变量、什么数据?对于时间刻度,国家30有30个值,对于供应商30有30个值,对于单位。。。我想
/**
 * Fills the 4 class member array variables country[], timeScale[], vendor[], 
 * and units[] with data obtained from the supplied CSV data file.<br><br>
 * 
 * @param filePath (String) Full Path and file name of the CSV data file.<br>
 * 
 * @param fileHasHeader (Boolean) Either true or false. Supply true if the CSV 
 * file does contain a Header and false if it does not.
 */
public void fillDataArrays(String filePath, boolean fileHasHeader) {
    long dataCount = fileLinesCount(filePath, fileHasHeader, true, true);

    /* Java Arrays will not accept the long data type for sizing
       therefore we cast to int.   */
    country = new String[(int) dataCount];
    timeScale = new String[(int) dataCount];
    vendor = new String[(int) dataCount];
    units = new double[(int) dataCount];
    int lineCounter = 0;    // counts all lines contained within the supplied text file

    try (Scanner reader = new Scanner(new File("DataFile.txt"))) {
        int indexCounter = 0;
        while (reader.hasNextLine()) {
            lineCounter++;
            String line = reader.nextLine().trim();
            // Skip comment and blank file lines.
            if (line.startsWith(";") || line.startsWith("#") || line.equals("")) {
                continue;
            }
            if (indexCounter == 0 && fileHasHeader) {
                /* Since we are skipping the header right away we 
                   now no longer need the fileHasHeader flag.   */
                fileHasHeader = false;
                continue;   // Skip the first line of data since it's a header
            }
            /* Split the raw data line based on a comma (,) delimiter. 
               The Regular Expression (\\s{0,},\\s{0,}") ensures that
               it doesn't matter how many spaces (if any at all) are 
               before OR after the comma, the split removes those 
               unwanted spaces, even tabs are removed if any.
            */
            String[] splitLine = line.split("\\s{0,},\\s{0,}");
            country[indexCounter] = splitLine[0];
            timeScale[indexCounter] = splitLine[1];
            vendor[indexCounter] = splitLine[2];
            /* The Regular Expression ("-?\\d+(\\.\\d+)?") below ensures
               that the value contained within what it to be the Units 
               element of the split array is actually a string representation
               of a signed or unsigned integer or double/float numerical value.
            */
            if (splitLine[3].matches("-?\\d+(\\.\\d+)?")) {
                units[indexCounter] = Double.parseDouble(splitLine[3]);
            }
            else {
                JOptionPane.showMessageDialog(this, "<html>An invalid Units value (<b><font color=blue>" + 
                        splitLine[3] + "</font></b>) has been detected<br>in data file line number <b><font " +
                        "color=red>" + lineCounter + "</font></b>. A value of <b>0.0</b> has been applied<br>to " + 
                        "the Units Array to replace the data provided on the data<br>line which consists of: " +
                        "<br><br><b><center>" + line + "</center></b>.", "Invalid Units Value Detected!", 
                        JOptionPane.WARNING_MESSAGE);
                units[indexCounter] = 0.0d;
            }
            indexCounter++;
        }
    }
    catch (IOException ex) {
        Logger.getLogger("fillDataArrays() ethod Error!").log(Level.SEVERE, null, ex);
    }
}
/// Fill the Arrays with data.
fillDataArrays("DataFile.txt", true);

// Display the filled Arrays.
System.out.println(Arrays.toString(country));
System.out.println(Arrays.toString(timeScale));
System.out.println(Arrays.toString(vendor));
System.out.println(Arrays.toString(units));