首页 > 解决方案 > 如何从 s txt 文件中获取名称列表以显示在组合框中?

问题描述

我被困在我一直在做的一个学校项目中。这是关于从我创建的 txt 文件中获取所有信息,并希望将产品名称获取到组合框中,其余产品详细信息显示在文本框的数字上。

txt 文件内容如下所示:

id|Category|Name|Price
0|Food|Pizza|$4.50
1|Drink|Pepsi|$2.10

等等。

这是我一直在处理的代码:(抱歉没有早点提供)

File product_file = new File("Product.txt");

Scanner scan = new Scanner(product_file);
scan.nextLine();//skip the column name/line
while (scan.hasNextLine()) {
  String line = scan.nextLine();//read each line
  String[] pieces = line.split("\\|");
  String product_name = pieces[2];

不知道如何将其链接到组合框。

标签: java

解决方案


我不确定您的问题是什么,但是如果您想从文本文件中读取数据,请尝试查看ScannerandFile类。

这会将文本文件直接打印到屏幕上,就像它出现在您的文本文件中一样:

File file = new File("myTextFile.txt");
Scanner scan = new Scanner(file);

while (scan.hasNextLine()) {
    System.out.println(scan.nextLine());
}

如果您需要将该数据解析为不同的变量/对象,您可以将所有文本转储为一个大字符串并将其拆分:

String str = "";
while (scan.hasNextLine()) {
    str += scan.nextLine();
}
String[] array = str.split("\\|");

例如,在您的文本文件中,array[5]将等于"Food".


推荐阅读