java - 如何从 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];
不知道如何将其链接到组合框。
解决方案
我不确定您的问题是什么,但是如果您想从文本文件中读取数据,请尝试查看Scanner
andFile
类。
这会将文本文件直接打印到屏幕上,就像它出现在您的文本文件中一样:
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"
.
推荐阅读
- django - 如何在我的“UsuarioSerializer”Django 中获取“ProductoSeralizer”列表
- python - pygame.event 和 pygame.fastevent 有什么区别?
- shell - 设置回传递给unix脚本的参数
- java - 我将如何编写一个 toString 并减少重复输出?
- r - 如何在 r 基础包图形中旋转绘图?
- sidekiq - Sidekiq 一直对 CSRF 保护大喊大叫,但路由安装在 Rails.application.routes.draw 中
- javascript - 如何在firebase存储中获取一个js文件并将其导入react?
- amazon-web-services - AWS Lightsail push-container-image,收到 NoCredentialProviders 错误?
- javascript - 组合堆栈、抽屉和选项卡导航器
- python-3.x - 如何在 Python 中模拟类实例(不是类函数)