java - Java,读取文件内容到arraylist
问题描述
我正在向 ArrayList 读取文件内容,以便以后可以操作数据。但是当我尝试打印控制台时,内容会重复显示。我在线希望能够打印五行。如何调整代码,以便在控制台上显示时只能显示五行并重复显示结果?在我的文件中
3456
1678
4354
2384
5634
阅读列出并显示到控制台后,结果是
3456
3456
1678
3456
1678
4354
3456
1678
4354
2384
3456
1678
4354
2384
5634
我只想显示五行。
3456
1678
4354
2384
5634
代码:
public void testread(){
System.out.println("Enter filename:\n");
String filename=Keyboard.readInput();
File myfile=new File(filename);
try (BufferedReader scanfile=new BufferedReader(new FileReader(myfile))) {
String str;
List<String>list=new ArrayList<String>();
while ((str=scanfile.readLine())!=null) {
int i;
list.add(str);
for (i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
} catch (IOException e) {
System.out.println("Error reading from file " + e.getMessage());
}
}
解决方案
您需要将您的 print for 循环移出您的 while 循环。然后,您的 while 循环的每次迭代都会打印列表中的每个值。像这样:
public void testread(){
System.out.println("Enter filename:\n");
String filename=Keyboard.readInput();
File myfile=new File(filename);
try(BufferedReader scanfile=new BufferedReader(new FileReader(myfile))){
String str;
List<String>
list=new ArrayList<String>();
while((str=scanfile.readLine())!=null)
{
int i;
list.add(str);
}
// then print the list
for(i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}catch (IOException e){
// Print error in case of failure.
System.out.println("Error reading from file " + e.getMessage());
}
}
推荐阅读
- python - 确定性随机函数
- mysql - 如何创建 SQL 查询以获取比较两列具有更高价值的所有项目
- javascript - 覆盖 React 的内部 `type`
- excel - 如何在 Excel 中选择显示的小数
- reactjs - 如何修复“./src/index.js Module not found: Can't resolve 'loadash” in my react app?
- websocket - istio 速率限制是否适用于 websocket 连接?
- android - AIR React Native 更新的 Play/App Store 限制
- sed - 使用 sed 从一个文件添加文本以匹配另一个文件的模式
- c# - 如何修复“执行当前 Web 请求期间发生未处理的异常。”
- python - 如何谷歌搜索返回英文结果