java - Java如何逐行读取文件并更改行的特定部分
问题描述
我是java新手,老师给了我们一个项目作业。我必须实现逐行读取文件,以逗号分割行并将部分存储在多维数组中,更改行的特定部分(我想更改数量)。给定文件:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
我尝试了此代码,但无法更改特定部分。
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
非常感谢!
解决方案
首先,您需要读取文件。有很多方法可以做到这一点,其中之一是:
BufferedReader s = new BufferedReader(new FileReader("filename"));
这允许您执行 s.readLine() 逐行读取它。您可以使用 while 循环将其读取到最后。请注意,如果到达文件末尾, readLine 将返回 null。然后,对于每一行,你想用昏迷来分割它们。您可以使用字符串的拆分方法:
line.split(",");
将它们放在一起,并为 IOException 使用 try-catch,您将得到:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
如果你最后真的需要一个二维数组,你可以这样做:
String[][] array = new String[0][0];
array = result.toArray(array);
然后您已经以您想要的格式读取了文件,您现在可以修改您解析的数据。
推荐阅读
- asp.net-mvc - 在 AspNetRoles 表标识中添加新角色
- javascript - 如何使用功能组件更新 Redux 状态?
- javascript - 没有任何解决方案可以从 Chrome 运行 Node.JS 代码吗?
- spring-boot - Spring Boot 推送通知
- javascript - Redux:为什么 store.getState() 与 useSelector 返回不同的值?
- excel - VBA AES CBC 加密
- r - 为什么 return(pval) 给出标准。结果是错误而不是p值?
- swiftui - 如何在 SwiftUI 应用中保存和加载 ARWorldMap?
- java - 如何使用默认方法返回功能接口的逆接口
- angular - 来自子域 A 的 Cookie 未发送到子域 B