我的目标是读入一个文本文件,并将每个元素添加到一个简单的数组中(这些元素由逗号分隔)。最后一个方法readData()是我不知道的方法。

到目前为止我的代码:

public class VersionChooser {

private Scanner scan;
private StockManager aManager = new StockManager("StockManager");

public VersionChooser() {
    this.scan = new Scanner(System.in);
}

public void chooseVersion() {
    this.readData();
    this.runTextOption();
}

private void runTextOption() {
    StockTUI tui = new StockTUI(this.aManager);
}

public StockManager readData() {
    String fileName;
    System.out.println("Enter the name of the file to be used");
    fileName = this.scan.nextLine();
    System.out.println(fileName);
    try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
            StandardCharsets.UTF_16)) {
        for (String line; (line = br.readLine()) != null;) {
            final String[] data = line.split(",");
            StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
            this.aManager.getStockList().add(record);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }


    return null;
}
}


库存记录:

public class StockRecord {
private String date;
private double closingPrice;

public StockRecord(String date, double closingPrice) {
    this.date = date;
    this.closingPrice = closingPrice;
}

public String getDate() {
    return this.date;
}

public double getClosingPrice() {
    return this.closingPrice;
}
public String toString() {
    return "On " + this.date + " this stock had a closing price of $"
            + this.closingPrice;
}
}

最佳答案

步骤1:逐行读取文件。

第2步:用“,”分隔行

步骤3:将String []构造为StockRecord。

try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
            StandardCharsets.UTF_8)) {
        List<StockRecord> stocks = new ArrayList<StockRecord>();
                    br.readLine() ; // to avoid first line
        for (String line; (line = br.readLine()) != null;) { // first step
            final String[] data = line.split(",");       // second step
            StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
            stocks.add(record);    // third step
        }
    } catch (IOException e) {
        e.printStackTrace();
    }


您的stockRecord没有所有记录。为了演示的目的,我确实假设2个元素是收盘价。相应地改变

关于java - 如何将String.split与文本文件一起使用以添加到简单数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23115885/

10-14 14:49
查看更多