如何将csv文件中的每列分配为int数?

  • 本文关键字:分配 int csv 文件 java csv
  • 更新时间 :
  • 英文 :


新手来了!

我已经学会了如何读取csv文件并将其显示到控制台,但这次我需要将csv文件的每一列分配为int数字并返回该方法,以便当我键入number(1)时,该文件的第一列将显示到屏幕上。

public double runAggregator(int i) throws IOException {    
StockFileReader stReader = new StockFileReader (file);

List<String> Column = st.readFileData();

CSV文件的每个数据行都很可能是逗号(,)分隔的,所以当您读取每行时,将其分开,然后显示您想要的列,例如:

public static void readAndDisplayDataColumn(String csvFilePath, int literalDataColumnToDisplay) throws IOException {
if (throws literalDataColumnToDisplay < 1) {
System.err.println("readAndDisplayDataColumn() method Error! " + 
"Invalid column number (" + literalDataColumnToDisplay + 
") supplied!");
return;
}
try (BufferedReader reader = new BufferedReader(new FileReader(csvFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] columnData = line.split("\s*,\s*);
System.out.println(columnData[literalDataColumnToDisplay - 1]);
}
}
}

将显示文件中每个数据行的第3列。

您将注意到,从literalDataColumnToDisplay中减去了1。这是因为数组的第一个元素(在本例中称为列)位于索引0,而desiredLiteralColumnNumber的字面值为3。例如,如果我们想要第1列的数据,literalDataColumnToDisplay将包含1的值,要从数组中获得实际的第一个元素,我们需要减去1以获得索引值0。

这应该可以让你开始。

EDIT:基于注释:

您已经知道StockFileReader#readFileData()方法返回String (List<String>)的List Interface,因此您需要遍历List以显示所需列,例如:

// Assuming i is the column number.
// Don't have a clue why this method returns a double because you supply no information whatsoever.
public double runAggregator(int i) throws IOException {    
StockFileReader stReader = new StockFileReader(file);
List<String> dataLines = stReader.readFileData();
for (String line : dataLines) {
String[] columnData = line.split("\s*,\s*);
System.out.println(columnData[i - 1]);
}
// whatever else you want to do in this method.
}

也许你想做的是返回double中特定列的所有内容数据类型数组而不是单双的。如果是这种情况,那么这可能是a做得好:

public double[] runAggregator(int i) throws IOException {    
StockFileReader stReader = new StockFileReader(file);
List<String> dataLines = stReader.readFileData();
double[] columnArray = new double[dataLines.size()];
for (int i = 0; i < dataLines.size(); i++) {
String[] columnData = dataLines.get(i).split("\s*,\s*);
columnArray[i] = Double.parseDouble(columnData[i - 1]);
}
return columnArray;
}

使用并显示返回的结果:

int columnNumber = 3;
try {
double[] columnValues = runAggregator(int columnNmber);
} catch(IOException ex) {
System.err.println(ex.getMessage());
}
// Display column data:
System.out.println("Column " + columnNumber + " Data:
for (double d : columnValues) {
System.out.println(d);
}