java语言实现”shopping.txt"文件读写,卖家:天猫tmall。芒果198元,蓝莓78元,大枣160元。 卖家:京东jd。笔记本3500元,硬盘1480元。 卖家:得到app。吴军299元,熊逸199元,严伯钧199元。 卖家:抖音。勿忘我19.9 海鲜大礼包99元。 要求按行读取购物单,并在该行的后面加上消费总额,然后将该行写到一个名字为buyingList.txt的文件中。 卖家:天猫tmall。芒果198元,蓝莓78元,大枣160元。消费总额:436.0元。 卖家:京东jd。笔记本3500元,硬盘1480元。消费总额:4980.0元。 卖家:得到app。吴军299元,熊逸199元,严伯钧199元。消费总额:697.0元。 卖家:抖音。勿忘我19.9 海鲜大礼包99元。消费总额:118.9元。
时间: 2023-09-04 15:15:25 浏览: 65
以下是Java语言实现读写"shopping.txt"文件的示例代码:
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ShoppingFileIO {
public static void main(String[] args) {
String fileName = "shopping.txt";
File file = new File(fileName);
File outputFile = new File("buyingList.txt");
// 写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
String[] items = line.split("。");
double total = 0.0;
for (int i = 1; i < items.length; i++) {
String item = items[i].trim();
if (item.endsWith("元")) {
String priceStr = item.substring(0, item.indexOf("元"));
double price = Double.parseDouble(priceStr);
total += price;
}
}
writer.write(line + "消费总额:" + total + "元。\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件并输出到控制台
try (BufferedReader reader = new BufferedReader(new FileReader(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码首先创建了一个名为"shopping.txt"的文件,并将各个卖家的商品信息写入文件中。然后创建一个名为"buyingList.txt"的文件,并使用BufferedWriter类按行读取"shopping.txt"文件中的购物单,并在该行的后面加上消费总额,最后将该行写入"buyingList.txt"文件中。需要注意的是,需要在代码中加入异常处理机制以避免程序出错。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)