java - 使用 Java 将文本文件中的内容读入 ArrayList
问题描述
我在将内容从文件移动到 ArrayList 时遇到问题。用户通过他想要添加到 ArrayList 的索引从文件中选择一行。我试过 quick.add(new Pastatas()); 但正如我所见,它将在那里添加我的空构造函数。
private void myobj() {
File FILE = new File(filex);
if (FILE.exists() && FILE.length() > 0) {
try {
Scanner SC = new Scanner(FILE);
for (int i = 0; i < FILE.length(); i++) {
if (SC.hasNextLine()) {
String storage = SC.nextLine();
System.out.println("ID: " + i + " " + storage);
}
}
System.out.println("select one.");
Scanner sc = new Scanner(System.in);
int userInputas = Integer.parseInt(sc.nextLine());
for (int j = 0; j < FILE.length(); j++) {
if (userInputas == j) {
quick.add(/*Probably problem here*/)
}
}
} catch (IOException e) {
System.err.println(e.getMessage() + "error");
}
}
解决方案
Path, Paths, Files
对此类任务使用较新的。
Path path = Paths.get(filex);
List<String> lines = Files.readAllLines(path);
System.out.println("Select one.");
Scanner sc = new Scanner(System.in);
int lineno = Integer.parseInt(sc.nextLine()); // Maybe 1 based
int index = lineno - 1; // Zero based index
if (0 <= index && index < lines.size()) {
String line = lines.get(index);
System.out.println("Selected: " + line);
quick.add(line);
}
逻辑错误:
FILE
(或Path
以上)只是文件的可能不存在的名字对象/名称。长度是字节数,文件大小。因此,对于选择文本行,必须执行不同的操作,例如打开、读取并最终关闭文件。该类Files
提供实用功能来执行诸如加载所有行之类的操作。
阅读您的评论后;也许更像:
quick.add(new Pastatas(line));
事实上,如果文件不是文本文件,我们需要知道文件是如何填充的。
推荐阅读
- c# - 如何对列表进行排序
通过对象中的属性,根据属性的逗号分隔字符串 - powershell - 外壳 | 有没有办法过滤掉数组中小于 6 个月大的项目?
- angular - 如何将开源 Angular 组件的本地克隆版本包含到 Angular 项目中?
- html - HTML 和 CSS 表格/网格设计
- html - 如何在 CSS 蒙版内有阴影?
- javascript - 将 TensorFlowJS MobileNet + KNN 保存到 TFLite
- flutter - Flutter:如何为两个小部件设置一个水龙头处理程序?
- xml - 如何使用 XMLStarlet / Xpath 选择里面的文本但排除一些内在
- java - 字符串开头的Java不可见空格
- ruby-on-rails - 如何在Ruby中迭代没有已知深度的深层嵌套哈希