java基础梳理-IO流

119 阅读1分钟

我是一名在校学生,这个寒假开始学java,在这个平台记录一下我的学习历程,希望激励我的同时也能帮助到正在学Java的小伙伴们。 加油加油加油

  • 文件File类
  • 字符流
  • 字节流
  • 节点流/处理流
  • properties类

思维导图

I_O流.png pdf

百度网盘链接:pan.baidu.com/s/14DOGQ0pa… 提取码:xz4i

练习题一

(1)在判断e盘下是否有文件夹mytemp,如果没有就创建mytemp
(2)在e:\mytemp目录下,创建文件hello.txt
(3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了
(4)并且在hello.txt文件中,写入hello,world~
String direPath = "d:\mytemp";
File file1 = new File(direPath);
if(file1.exists()){
    System.out.println("d:\mytemp文件存在");
}else{
    file1.mkdirs();
    System.out.println("文件夹创建成功");
}
String filePath = "hello.txt";
File file2 = new File(direPath, filePath);
BufferedWriter buff = null;
if(file2.exists()){
    System.out.println("d:\mytemp\hello.txt文件已存在");
}else{
    try {
        file2.createNewFile();
        System.out.println("文件创建成功");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
buff = new BufferedWriter(new FileWriter(file2));
buff.write("hello,world~");
buff.close();

练习题二

(1)要编写一个dog-properties
name=tom
age=5
color=red
(2)编写Dog类(name,age,color)创建一个dog对象,读取dog-properties用相应的内容完
成属性初始化,并输出
(3)将创建的Dog对象,序列化到文件dog.dat文件
main

//创建Properties对象
        Properties properties = new Properties();
        //加载
        properties.load(new FileReader("src\com\edu\exercise_\dog.properties"));
        //获取值
        String name = "";
        String age;
        String color = "";
        name = properties.getProperty("name");
        age = properties.getProperty("age");
        color = properties.getProperty("color");
        Dog dog = new Dog(name, Integer.parseInt(age), color);
        System.out.println(dog);
        //序列化到文件dog.dat文件
        String filePath = "d:\dog.dat";
//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//        oos.writeObject(dog);
//        oos.close();

        //进行反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//        System.out.println(ois.readObject());
        Dog dog1 = (Dog) ois.readObject();
        System.out.println(dog1.getName());
        ois.close();
    
Dog类
private String name;
private int age;
private String color;

public Dog(String name, int age, String color) {
    this.name = name;
    this.age = age;
    this.color = color;
}

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;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

@Override
public String toString() {
    return "Dog{" +
            "name='" + name + ''' +
            ", age=" + age +
            ", color='" + color + ''' +
            '}';
}