Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何读取java中有空列且只有一些数据的少数列的CSV文件?_Java_Csv_Stream - Fatal编程技术网

如何读取java中有空列且只有一些数据的少数列的CSV文件?

如何读取java中有空列且只有一些数据的少数列的CSV文件?,java,csv,stream,Java,Csv,Stream,我有下面这样的Test.csv文件,现在我想通过跳过空列(如果有)来使用JAVA读取csv文件。 如果total列为空,则我想跳过该列 111, ,John,2000, ,US 222, ,Alle,3000, ,China 333, ,Kite,4000,LCD,IND 444, ,King,5000,LED,Aust import java.io.File; import java.io.FileNotFoundException; import java.util.Scanne

我有下面这样的Test.csv文件,现在我想通过跳过空列(如果有)来使用JAVA读取csv文件。 如果total列为空,则我想跳过该列

111, ,John,2000,   ,US 
222, ,Alle,3000,   ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    public class Test {
        public static void main(String[] args) 
        {
            Scanner s = null;
            try {
                s = new Scanner(new File("D:/sri/Test.txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while (s.hasNextLine()) {
                String line = s.nextLine();
            }
        }
    }

在这里,我也可以读取空列。关于这一点,请您提出建议。

我建议您将SuperCSV与CsvBeanReader一起使用,您可以自定义一个CellProcessor,以便在数据为空时忽略行。

一个简单的解决方案是使用CsvReader并逐行读取,然后在解析器之后检查每个数据。一旦你得到一个空字符串,然后移动到下一行!

您可以使用util方法检查它是否为空字符串

public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

我还想通过只跳过空列来在数据库中插入该数据,那么我该如何实现呢?我想在数据库中动态插入该类型的csv文件。有时它可能包含空列,有时不包含空列。我如何实现?
Scanner s = null;
        try {
            s = new Scanner(new File("D:/sri/Test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (s.hasNextLine()) {
            String[] line = s.nextLine().split(",");
            for (String element : line) {
                if (!isBlank(element))
                    System.out.println(element);
            }

        }