将这个代码修改的简单一点
时间: 2024-11-13 07:18:51 浏览: 10
要简化这段代码,我们可以去掉一些不必要的复杂操作和异常处理,只保留基本的读取和写入数据功能。以下是简化后的例子:
```java
import java.io.*;
public class SimplifiedBookHandler {
public static void main(String[] args) {
List<Book> books = readBooksFrom("input.txt");
writeBooksTo(books, "output.txt");
}
private static List<Book> readBooksFrom(String fileName) {
List<Book> books = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(",");
Book book = new Book(Integer.parseInt(fields[0]), fields[1], fields[2], Double.parseDouble(fields[3]), Integer.parseInt(fields[4]));
books.add(book);
}
} catch (Exception e) {
System.out.println("Error reading file: " + e.getMessage());
}
return books;
}
private static void writeBooksTo(List<Book> books, String fileName) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
for (Book book : books) {
bw.write(book.toString() + "\n");
}
} catch (Exception e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
class Book {
int id;
String title;
String version;
double price;
int sales;
// 省略构造函数和toString()
}
```
在这个简化版中,我们直接使用逗号(`,`)而不是空格分隔字段,假设输入文件的格式已改变。同时移除了价格动态调整的部分,仅保留书本信息的读取和写入操作。错误处理也更简洁,只在出现异常时打印错误消息,而非详细堆栈跟踪。
阅读全文