[英]Read CSV file and use StringTokenizer
这是一个简单的家庭作业,在过去的几天里一直让我发疯。 如果我要使用几个数组,我可以在不久前完成,但是必须使用 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);
}
}
使用 java 8 中的Streams
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());
您还可以使用flatMap
函数检索单个列表中的所有元素
List<String> list = lines
.skip(1)
.map(line -> line.split(","))
.flatMap(Arrays::stream)
.collect(Collectors.toList());
首先,我认为您没有正确解释StringTokenizer
方法调用/返回类型。 数组对我来说没有多大意义。
您想遍历 csv 文件中的每一行,对吗? 您可以在循环的每一步创建一个新的StringTokenizer
,并使用它从每一行中获取您想要的内容。
清理你的do ... while
循环,让它看起来更像这样:
final String delimiter = ", ";
for(int lineNumber = 1; fileIn.hasNextLine(); ++lineNumber) {
String csvLine = fileIn.next();
if (lineNumber == 1) {
// this is your special case for the first line, handle it!
continue;
}
StringTokenizer tokenizer = new StringTokenizer(csvLine, delimiter);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
// do stuff with the tokens!
}
}
为什么要使用 StringTokenizer 数组? 尝试这个。
try{
StringTokenizer st=null;
FileReader inputFileReader = new FileReader("C:/Users/Cristian/Desktop");
BufferedReader inputStream = new BufferedReader(inputFileReader);
String inLine = null;
while((inLine = inputStream.readLine())!=null){
st = new StringTokenizer(inLine, ",");
System.out.println(st.nextToken());
System.out.println(st.nextToken());
System.out.println(st.nextToken());
}
}
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);
}
private static void readWithCsvBeanReader() throws Exception {
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
// the header elements are used to map the values to the bean (names must match)
final String[] header = beanReader.getHeader(true);
final CellProcessor[] processors = getProcessors();
CustomerBean customer;
while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) {
System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(),
beanReader.getRowNumber(), customer));
}
}
finally {
if( beanReader != null ) {
beanReader.close();
}
}
}
您将需要为您的业务对象定义一个bean ,并使用它代替 CustomerBean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.