1、BufferedReader的使用:
测试代码:
package test.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileReadToList {
public static void main(String[] args) {
// 文件路径
String filePath = "D:\\AA\\a.txt";
// 创建列表存储文件中的每一行
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
// 逐行读取直到文件末尾
while ((line = reader.readLine()) != null) {
// 将读取的每一行添加到列表中
lines.add(line);
}
// 遍历列表并打印每一行
for (String str : lines) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取文件时发生错误:" + e.getMessage());
}
}
}
运行结果如下;
2、BufferedWriter的使用:
测试代码:
package test.com;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class WriteListToFile {
public static void main(String[] args) {
// ArrayList集合,存储字符串。
List<String> strings = new ArrayList<>();
strings.add("第一行");
strings.add("第二行");
strings.add("第三行");
// 指定文件路径
String filePath = "E:\\Test\\a.txt";
// 使用try-with-resources语句来自动关闭BufferedWriter
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
// 遍历集合
for (String str : strings) {
// 将每个字符串写入文件,并在末尾添加换行符
writer.write(str);
writer.newLine(); // 写入一个新的行分隔符
}
// 由于使用了try-with-resources,不需要显式调用writer.close();
// 会在try块的末尾自动调用
} catch (IOException e) {
e.printStackTrace();
System.out.println("写入文件时发生错误:" + e.getMessage());
}
System.out.println("文件写入完成。");
}
}
运行结果如下:
3、文件到集合:
测试代码:
创建一个运动员类;
package test.com;
public class Athlete {
private String name;
private String gender;
private String nationality;
private double height; // 身高,单位cm
private double weight; // 体重,单位kg
// 构造方法
public Athlete(String name, String gender, String nationality, double height, double weight) {
this.name = name;
this.gender = gender;
this.nationality = nationality;
this.height = height;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
// toString方法(可选,用于打印Athlete对象的信息)
@Override
public String toString() {
return "Athlete{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", nationality='" + nationality + '\'' +
", height=" + height + "cm" +
", weight=" + weight + "kg" +
'}';
}
}
读取:E:\\Test\\athletes.txt 文本中的文件到集合:
package test.com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RandomRollCall {
public static void main(String[] args) {
List<Athlete> athletes = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("E:\\Test\\athletes.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\\s+"); // 使用一个或多个空格作为分隔符
if (fields.length >= 4) {
String name = fields[0];
String gender = fields[1];
String nationality = fields[2];
// 去除身高字符串中的 "cm" 后缀
String heightStr = fields[3].replace("cm", "").trim();
double height = Double.parseDouble(heightStr); // 解析为 double
Athlete athlete = new Athlete(name, gender, nationality, height,height);
athletes.add(athlete);
}
}
// 打印运动员信息
for (Athlete athlete : athletes) {
System.out.println(athlete); // 确保 Athlete 类有合适的 toString() 方法
}
} catch (IOException | NumberFormatException e) {
e.printStackTrace();
// 添加记录日志或通知用户的方法。
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果如下:
4、集合到文件;
测试代码:
创建一个鲜花类:
package test.com;
public class Flower {
private String name;
private String color;
private int petals;
private int quantity;
private String origin;
// 构造方法
public Flower(String name, String color, int petals, int quantity, String origin) {
this.name = name;
this.color = color;
this.petals = petals;
this.quantity = quantity;
this.origin = origin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPetals() {
return petals;
}
public void setPetals(int petals) {
this.petals = petals;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
// 格式化输出方法
public String toFormattedString() {
return String.format("%s,%s,%d,%d,%s", name, color, petals, quantity, origin);
}
}
将集合写入到:E:\\Test\\flowers.txt文本文件中。
package test.com;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FlowerListToFile {
public static void main(String[] args) {
List<Flower> flowers = new ArrayList<>();
flowers.add(new Flower("玫瑰", "红色", 26, 10, "中国"));
flowers.add(new Flower("郁金香", "黄色", 6, 20, "荷兰"));
flowers.add(new Flower("菊花", "白色", 100, 5, "日本"));
// 文件路径
String filePath = "E:\\Test\\flowers.txt";
// 写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (Flower flower : flowers) {
writer.write(flower.toFormattedString());
writer.newLine(); // 换行
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("鲜花数据已写入文件:" + filePath);
}
}
运行结果如下: