1.通过打印流完成复制文本文件
import java.io.*;
public class PrintDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("d:\\file.txt"));
PrintWriter printWriter = new PrintWriter(new FileOutputStream("d:\\copy.txt", true));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
printWriter.write(line);
}
bufferedReader.close();
printWriter.close();
}
}
2.编写程序,通过序列化流与反序列化流完成从file.txt文件存取对象的操作
import java.io.*;
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student student1 = new Student("张三", 20);
Student student2 = new Student("李四", 21);
Student student3 = new Student("王五", 22);
ArrayList<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("c.txt"));
out.writeObject(list);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("c.txt"));
Object object = in.readObject();
ArrayList<Student> list1 = (ArrayList<Student>) object;
for (Student s : list1) {
System.out.println(s.getName() + "==" + s.getAge());
}
}
}
class Student implements Serializable {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
运行结果为:
3.编写程序,判断文件中是否有指定的键如果有就修改值
需求:有一个文本文件file.txt,我知道数据是键值对形式的,但是不知道内容是什么。
请写一个程序判断是否有"lisi"这样的键存在,如果有就改变其实为"100"
file.txt文件内容如下:
zhangsan = 90
lisi = 80
wangwu = 85
import java.io.*;
import java.util.Properties;
import java.util.Set;
public class FileTest {
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
Reader r = new FileReader("d:\\file.txt");
prop.load(r);
r.close();
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
if ("lisi".equals(key)) {
prop.setProperty(key, "100");
break;
}
}
Writer w = new FileWriter("d:\\file.txt");
prop.store(w, null);
w.close();
}
}