[英]Reading a .CSV file using Scanner?
我有一個.CSV文件,其中包含一行內容:
Detroit 25 4 7 W Green Bay 7 7 4 L
我用輸入名稱創建一個新的掃描儀
Scanner input = new Scanner(file); //file here is the .csv file
如果我打印input.next(),將顯示以下內容:
Detroit,25,4,7,W,Green
Bay,7,7,4,L
如果我創建一個新的數組並指定分隔符,如下所示:
String[] list = input.next().split(",");
然后打印數組的索引
System.out.println(list[2]);
我得到這個:
Detroit,25,4,7,W,Green
7
而不是4。如何將.csv的每個值放在其自己的邏輯索引中? 例:
list[0] = Detroit list[1] = 25 and so on.
這是我的完整代碼:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.geometry.*;
import java.util.*;
import java.io.*;
public class POS extends Application
{
private Button runBtn = new Button("Run");
@Override
public void start(Stage stage)
{
GridPane pane = new GridPane();
VBox vBox = new VBox(20);
vBox.setPadding(new Insets(15));
Button selectBtn = new Button("Select File");
selectBtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
vBox.getChildren().add(selectBtn);
selectBtn.setOnAction(e->
{
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("TEXT files (*.csv)", "*.CSV", ".xlsv", ".XLSV");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(stage);
run(file);
});
RadioButton weekBtn = new RadioButton("Current Week");
RadioButton seasonBtn = new RadioButton("Entire Season");
runBtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
seasonBtn.setDisable(true);
vBox.getChildren().add(weekBtn);
vBox.getChildren().add(seasonBtn);
vBox.getChildren().add(runBtn);
pane.add(vBox, 0, 0);
Scene scene = new Scene(pane, 500, 200);
stage.setScene(scene);
stage.setTitle("POS");
stage.show();
}
public void run(File file)
{
runBtn.setOnAction(e->
{
try
{
Scanner input = new Scanner(file);
input.nextLine();
System.out.println(input.next());
sortFile(file, input);
input.close();
}
catch (InputMismatchException ex)
{
System.out.println("Error you seem to have typed the wrong type of file");
}
catch(IOException ex)
{
System.out.println("Error, file could not be found");
}
});
}
public ArrayList<String> sortFile(File file, Scanner input)
{
String[] list = input.next().split(",");
System.out.println(list[2]);
if (input.hasNext())
{
return null;
}
return null;
}
}
您的cvs文件似乎采用制表符分隔格式。 您應該使用:
String[] list = input.nextLine().split("\t");
它應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.