01.从文件中读取数据,将数据存放到ArrayList数组,然后遍历数据
一、要求:
1.定义一个图书类:Book,要求有如下属性:
图书名称(String),价格(double),数量(int).
要求:
1).成员属性私有化;
2).定义无参和全参的构造方法;
3).为每个成员属性定义get和set方法;
2.在项目根目录下手动创建一个book.txt文件,存放以下数据:(图书名称,价格,图书数量)
西游记,30.60,1888
红楼梦,38.80,2888
三国演义,25.60,3888
水浒传,32.80,5888
3.在测试类的main方法中,完成以下要求:
①定义集合ArrayList,并声明Book泛型;
②将文件内容读到程序中,并将每一条图书信息进行解析,分别把各个属性封装成一个Book对象,存储到创建的集合中.
③遍历集合,计算出每种书的总价,与所有书的总价打印到控制台
二、代码实现
1.Book类的实现代码:
public class Book {
String bookName;
double price;
int count;
public Book() {
}
public Book(String bookName, double price, int count) {
this.bookName = bookName;
this.price = price;
this.count = count;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return bookName + "," + "共计" + (price * count) + "元";
}
}
2.测试类的实现代码:
public class Demo1 {
public static void main(String[] args) throws Exception {
ArrayList<Book> list = new ArrayList<>();
FileReader fileReader = new FileReader(new File("book.txt"));
BufferedReader reader = new BufferedReader(fileReader);
String str = null;
while ((str = reader.readLine()) != null) {
String[] split = str.split(",");
if (split.length == 3) {
list.add(new Book(split[0], Double.parseDouble(split[1]), Integer.parseInt(split[2])));
}
}
for (Book book : list) {
System.out.println(book);
}
}
}
02.使用Properties类将文件中数据修改并写入新的文件
一、要求
1.在项目根目录下创建fuhao.txt文件,将以下代表富豪名称和财富的“键值对”手动存到文件中
fuhao.txt文件中内容如下:
王健林=2050亿
马云=2000亿
李嘉诚=1750亿
李兆基=1660亿
马化腾=1520亿
丁磊=1250亿
宗庆后=1120亿
姚振华=1050亿
郑家纯=1050亿
王卫=900亿
2.利用所学的Properties类的相关知识,将文件内容读取到项目中,判断“键值对”中是否有王卫的数据,如果有,将其对应的身价修改为1860亿,并利用Properties类的相关知识把修改后的最新数据写入到新的文件newfuhao.txt中。
二、代码实现
注:读取.txt文件想要正常打印出来需要使用字符流
public class Demo2 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("fuhao.txt"));
String value = properties.getProperty("王卫");
if (value != null) {
properties.setProperty("王卫", "1860亿");
}
FileWriter writer = new FileWriter("newfuhao.txt");
properties.store(writer, null);
writer.close();
}
}