读取CSV文件并使用StringTokenizer

Cri*_*yes 2 java csv string tokenize

这是一个简单的家庭作业,过去几天一直让我发疯.如果我要使用几个阵列,我可以在不久前完成它但是必须使用StringTokenizer让我疯了.

我遇到的主要问题是读取CSV文件.我不知道该怎么做,之前的在线搜索只提出了超级强烈的解决方案,这对于像我这样的初学者来说太过分了.

这是我的代码.如你所见,我不知道是否使用.nextLine().NextToken().似乎都没有用.

对于那些想知道作业的人来说,基本上是用逗号分隔前4个产品,然后读取其余行作为这4个产品的评级.基本上6行,4列.第一行是产品,其余的是评级.

import java.util.StringTokenizer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ProductRating {

public static void main(String[] args) {
    // TODO Auto-generated method stub


    Scanner fileIn=null;
    try{
        fileIn = new Scanner(
                 new FileInputStream("C:/Users/Cristian/Desktop"));
    }
    catch (FileNotFoundException e)
     {  // This block executed if the file is not found
        // and then the program exits
    System.out.println("File not found.");
    System.exit(0);
    }

    //If Opened File Successful this runs
    String products = "A";
    String rantings ="0";
    System.out.println("Gathering Ratings for Products");

    do{

        String delimiters = ", ";

        StringTokenizer gatherProducts[]=new StringTokenizer[inputLine, delimeters];
        gatherProducts=fileIn.nextLine();

    }while(fileIn.hasNextLine()==true);

}   

}
Run Code Online (Sandbox Code Playgroud)

her*_*rau 7

Streams在Java 8中使用API的简单方法(带标题行的csv):

Path path = Paths.get("C:/Users/Cristian/Desktop"); // path to folder
    Path file = path.resolve("file.csv"); // filename 
    Stream<String> lines = Files.lines(file);
    List<String[]> list = lines
            .skip(1)
            .map(line -> line.split(","))
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

您还可以使用该flatMap函数检索单个列表中的所有元素

         List<String> list = lines
            .skip(1)
            .map(line -> line.split(","))
            .flatMap(Arrays::stream)
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)