从文件中读取预订机票,并将预订的航班写入文件。使用BufferedReader读取文件,该文件每行总是有10个元素,用逗号分隔。接下来,使用BufferedWriter在进行保留后写入文件。
时间: 2024-04-30 07:23:17 浏览: 50
Java 按行读取文件按行写入文件并以空格分割字符串的方法
以下是Java代码示例:
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FlightBooking {
public static void main(String[] args) {
String inputFilePath = "input.txt";
String outputFilePath = "output.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));
String line;
while ((line = reader.readLine()) != null) {
String[] booking = line.split(",");
String flightNumber = booking[0];
String departure = booking[1];
String destination = booking[2];
String date = booking[3];
String time = booking[4];
String firstName = booking[5];
String lastName = booking[6];
String email = booking[7];
String phone = booking[8];
String seat = booking[9];
// Do something with the booking information, e.g. write to a database
// Write the booking to the output file
writer.write(flightNumber + "," + departure + "," + destination + "," + date + "," + time + "," + firstName + "," + lastName + "," + email + "," + phone + "," + seat);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("Bookings written to file: " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码将预订信息从文件中读取到字符串数组中,然后将其写入输出文件。请注意,我们使用BufferedReader和BufferedWriter来进行文件的读写,以提高效率。同时,我们还在输出文件中添加了一个新行符。
阅读全文