栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java IO流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java IO流

IO流 文件

常用的文件操作

01:

package FileDemo01;

import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;

public class FileCreate {
    public static void main(String[] args) {



    }

    @Test
    public void create01()
    {
        String filePath = "D:\JavaPathExercise\new1.txt";
        File file = new File(filePath);

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("success to create");
    }

    @Test
    public void create02()
    {
        File parentFile = new File("D:\JavaPathExercise");
        String fileName = "new2.txt";
        //这里的file对象,在java程序中,只是一个对象
        //只有执行了createNewFile方法,才会成为真正的,在硬盘创建该文件
        File file = new File(parentFile,fileName);

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("success to create");
    }

@Test
    public void create03()
    {
        String parentPath = "D:\";
        String filePath = "JavaPathExercise\new03.txt";

        File file = new File(parentPath,filePath);

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("success to create");
    }


}




02:

package FileDemo01;

import org.junit.jupiter.api.Test;

import java.io.File;

public class FileInformation {
    public static void main(String[] args) {

    }


    @Test
    public void info()
    {
        File file = new File("D:\JavaPathExercise\new1.txt");

        System.out.println("file name = "+file.getName());

        System.out.println("文件的绝对路径 = "+file.getAbsolutePath());

        System.out.println("文件父级目录 = "+file.getParent());

        System.out.println("文件字节大小 = "+file.length());

        System.out.println("文件是否存在 = "+file.exists());//T

        System.out.println("是不是一个文件 = "+file.isFile());//T

        System.out.println("是不是一个目录 = "+file.isDirectory());//F

    }

}


03:

package FileDemo01;

import org.junit.jupiter.api.Test;

import java.io.File;

public class Director_Demo {
    public static void main(String[] args) {

    }

    @Test
    public void m1()
    {
        String filePath = "D:\JavaPathExercise\new1.txt";
        File file = new File(filePath);
        if (file.exists())
        {

            if (file.delete())
            {
                System.out.println("success to delete");
            }
            else
            {
                System.out.println("fail");
            }
        }
        else
        {
            System.out.println("the file does not exist");
        }
    }


    @Test
    public void m2()
    {
        String filePath = "D:\demo02";//删除的是目录
        File file = new File(filePath);
        if (file.exists())
        {

            if (file.delete())
            {
                System.out.println("success to delete");
            }
            else
            {
                System.out.println("fail");
            }
        }
        else
        {
            System.out.println("the file does not exist");
        }
    }


    @Test
    public void m3()
    {
        String filePath = "D:\JavaPathExercise02";//删除的是目录
        File file = new File(filePath);
        if (file.exists())
        {

            System.out.println("the file exists");
        }
        else
        {
           if (file.mkdirs())
           {
               System.out.println("success to create");
           }
        }
    }


}



IO流原来及流的分类


IO流体系图-常用的类

FileInputStream介绍

01:

package FileDemo01;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStream {
    public static void main(String[] args) {

    }

    @Test
    public void readFile01()
    {
        String filePath = "D:\JavaPathExercise\new1.txt";
        java.io.FileInputStream fileInputStream = null;
        int readData = 0;
        try {

             fileInputStream = new java.io.FileInputStream(filePath);

            while((readData = fileInputStream.read())!=-1)
            {
                System.out.print((char)readData);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void readFile02()
    {
        String filePath = "D:\JavaPathExercise\new1.txt";
        byte[] buf = new byte[8];
        java.io.FileInputStream fileInputStream = null;
        int readLen = 0;
        try {

            fileInputStream = new java.io.FileInputStream(filePath);

            while((readLen = fileInputStream.read(buf))!=-1)
            {
                System.out.print(new String(buf,0,readLen));
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

FileOutputStream介绍


01:

package FileDemo01;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    @Test
    public void writeFile()
    {
        String filePath = "D:\JavaPathExercise\new4.txt";
        FileOutputStream fileOutputStream = null;

        try {
           // fileOutputStream = new FileOutputStream(filePath);  //会覆盖原txt里面的内容
            fileOutputStream  = new FileOutputStream(filePath,true);//追加

            //fileOutputStream.write('a');

            String str = "hello,world";
            //str.getBytes()将字符串转成字符数组
           // fileOutputStream.write(str.getBytes());
            fileOutputStream.write(str.getBytes(),0,str.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

小练习

01:

package FileDemo01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {


        String srcFilePath = "D:\JavaPathExercise\luf.jpg";
        String destFilePath = "D:\JavaPathExercise02\tyc.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new java.io.FileInputStream(srcFilePath);
            fileOutputStream =  new java.io.FileOutputStream(destFilePath);

            byte[] buf = new byte[1024];
            int readLen = 0;
            while((readLen = fileInputStream.read(buf))!=-1)
            {
                //边读边写
                fileOutputStream.write(buf,0,readLen);
            }
            System.out.println("ok!!!");

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }


}

01:

package FileReaderandFileWritter;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {

        String filePath = "D:\JavaPathExercise\new5.txt";
        FileReader fileReader = null;

        int data = 0;
        try {
            fileReader = new FileReader(filePath);

            while((data = fileReader.read())!=-1)
            {
                System.out.print((char)data);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {

            if (fileReader!=null)
            {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileReader案例

01:

package FileReaderandFileWritter;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {

        String filePath = "D:\JavaPathExercise\new5.txt";
        FileReader fileReader = null;

       int readLen = 0;
       char[] buf = new char[8];

        try {
            fileReader = new FileReader(filePath);

            while((readLen = fileReader.read(buf))!=-1)
            {
                System.out.print(new String(buf,0,readLen));
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {

            if (fileReader!=null)
            {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

FileWriter案例

01:

 public void close() throws IOException {
        se.close();
    }
}


 public void close() throws IOException {
        synchronized (lock) {
            if (closed)
                return;
            try {
                implClose();
            } finally {
                closed = true;
            }
        }
    }



void implClose() throws IOException {
        flushLeftoverChar(null, true);
        try {
            for (;;) {
                CoderResult cr = encoder.flush(bb);
                if (cr.isUnderflow())
                    break;
                if (cr.isOverflow()) {
                    assert bb.position() > 0;
                    writeBytes();
                    continue;
                }
                cr.throwException();
            }

            if (bb.position() > 0)
                writeBytes();
            if (ch != null)
                ch.close();
            else {
                try {
                    out.flush();
                } finally {
                    out.close();
                }
            }
        } catch (IOException x) {
            encoder.reset();
            throw x;
        }
    }


private void writeBytes() throws IOException {
        bb.flip();
        int lim = bb.limit();
        int pos = bb.position();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

            if (rem > 0) {
        if (ch != null) {
            if (ch.write(bb) != rem)
                assert false : rem;
        } else {
            out.write(bb.array(), bb.arrayOffset() + pos, rem);
        }
        }
        bb.clear();
        }
节点流和处理流

01:

模拟一波!

package FileReaderandFileWritter;

public abstract class Reader_Demo {
    public void readFile()
    {
    }

    public void readString()
    {
    }
    
    //在Reader_Demo抽象类,使用read方法统一管理也可以
    //public abstract void read();
}


class BufferedReader_ extends Reader_Demo
{
    private Reader_Demo reader;

    public BufferedReader_(Reader_Demo reader) {
        this.reader = reader;
    }

    //让方法更加灵活,多次读取文件
    public void readFiles(int num)
    {
        for (int i = 0;i 
BufferedReader 

01:

package FileReaderandFileWritter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderDemo1 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\JavaPathExercise\new10.java";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

        String line;
        while((line = bufferedReader.readLine())!=null)
        {
            System.out.println(line);
        }

        bufferedReader.close();
    }
}

BufferedWriter

01:

package FileReaderandFileWritter;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterDemo01 {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\JavaPathExercise\new10.txt";

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        //BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));//追加
        bufferedWriter.write("hello,world");
        bufferedWriter.newline();
        bufferedWriter.write("hello,world");

        bufferedWriter.close();
    }
}

01:

package FileReaderandFileWritter;

import java.io.*;
import java.io.FileReader;

public class BufferedCopy {
    public static void main(String[] args) {

        //BufferedReader 和BufferedWriter 是安装字符操作
        //不要去操作二进制文,可能造成文件损失
        
        String srcFilePath = "D:\JavaPathExercise\new1.txt";
        String destFilePath = "D:\JavaPathExercise01\new2.txt";
        BufferedReader br = null;
        BufferedWriter bw = null;


        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));

            String line;
            while((line = br.readLine())!=null)
            {
                bw.write(line);
                bw.newline();
            }

        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {

            try {
                if (br != null) {
                    br.close();
                }

                if (bw != null) {
                    bw.close();
                }
            }catch(IOException e)
            {
                e.printStackTrace();
            }

        }


    }
}

BufferedInputStream

BufferedOutputStream

01:

package FileReaderandFileWritter;

import java.io.*;

public class BufferedCopy01 {
    public static void main(String[] args) throws IOException {
        //BufferedOutputStream 和 BufferedInputStream使用
        //可以完成二进制文件拷贝
        //字节流可以操作二进制文件
        String srcFilePath = "D:\JavaPathExercise\new1.jpg";
        String destFilePath = "D:\JavaPathExercise\hsp.jpg";

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        bis = new BufferedInputStream(new FileInputStream(srcFilePath));
        bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

        byte[] buff = new byte[1024];
        int readLen = 0;

        while((readLen = bis.read(buff))!=-1)
        {
            bos.write(buff,0,readLen);
        }

        System.out.println("success to copy!!!");

        if (bis!=null)
        bis.close();

        if (bos!=null)
        bos.close();

    }
}

对象流


ObjectOutputStream案例

01:

package FileReaderandFileWritter;

import java.io.*;

public class ObjectOutStreamDemo {
    public static void main(String[] args) throws IOException {

        String filePath = "D:\JavaPathExercise\data.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

        oos.writeInt(100);//int -> Integer(实现了Serializable)

        oos.writeBoolean(true);//boolean -> Boolean (实现了Serializable)

        oos.writeChar('a');//char -> Character(实现了Serializable)

        oos.writeDouble(9.5);//double -> Double (实现了 Serializable)

        oos.writeUTF("hspjiaoyu");//String 实现了 Serializable



        oos.writeObject(new Dog("wancai",10));

        oos.close();

        System.out.println("data niub");



    }
}

class Dog implements Serializable
{
    private String name;
    private int age;

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



ObjectInputStream案例

01:

package FileReaderandFileWritter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

public class ObjectInputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String filePath = "D:\JavaPathExercise\data.dat";

        java.io.ObjectInputStream ois = new java.io.ObjectInputStream(new FileInputStream(filePath));

        //1.读取(反序列化)的顺序需要和你保存数据(序列化)顺序一致
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        Object dog = ois.readObject();
        System.out.println(dog.getClass());
        System.out.println(dog);
        //1.如果我们希望调用Dog的方法,需要向下转型
//2.需要我们将Dog类的定义,放在到可以引用的位置
        Dog dog2 = (Dog)dog;
        System.out.println(dog2.getName());

        ois.close();
    }
}


class Dog implements Serializable
{
    private String name;
    private int age;

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

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + ''' +
                ", 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;
    }
}



注意事项和细节说明

标准输入输出流

01:

package FileReaderandFileWritter;

public class InputAndOutputDemo {
    public static void main(String[] args) {
        //System类的public final static InputStream in = null;
        //System.in 编译类型 InputStream
        //System.in 运行类型 BufferedInputStream
        System.out.println(System.in.getClass());//class java.io.BufferedInputStream

        //1.System.out public final static PrintStream out = null;
        //2.编译类型 PrintStream
        //3.运行类型 PrintStream
        System.out.println(System.out.getClass());//class java.io.PrintStream
    }
}

转换流InputStreamReader 和OutputStreamWriter

01:

package FileReaderandFileWritter;

import java.io.*;

public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {

        String filePath = "D:\JavaPathExercise\new1.txt";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");

        BufferedReader br = new BufferedReader(isr);


        String s = br.readLine();
        System.out.println(s);

        br.close();
    }

}

02:

package FileReaderandFileWritter;

import java.io.*;

public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        String filePath = "D:\JavaPathExercise\hsp.txt";
        String charSet = "gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        
        osw.write("tfgyuhjikfghbjk你好");
        
        osw.close();

        System.out.println("according to"+charSet+"success");
    }
}

打印流PrintStream和PrintWriter
  • 打印流只有输出流,没有输入流


01:

package FileReaderandFileWritter;

import java.io.IOException;
import java.io.PrintStream;

public class PrintStreamDemo {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        out.print("john,hello");//底层是write()

        out.write("ajksdadas".getBytes());




        out.close();


        //我们可以去修改打印流输出的位置/设备
        //1.输出修改成"D:\JavaPathExercise\new11.txt"
        //2."hello,world"就会输出到该文件中
        System.setOut(new PrintStream("D:\JavaPathExercise\new11.txt"));
        System.out.println("hello,world");

//        public static void setOut(PrintStream out) {
//            checkIO();
//            setOut0(out);//native方法,修改了out
//        }

    }
}

02:

package FileReaderandFileWritter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriterDemo01 {
    public static void main(String[] args) throws IOException {
        //PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("D:\JavaPathExercise\new12.txt"));
        printWriter.print("hello,world");
        printWriter.close();//flush + 关闭流 真正写数据的是flush,所以一定要记得写close();
    }
}

Properties类 引出

01:

package FileReaderandFileWritter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Properties01 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("src\mysql.properties"));

        String line = "";
        while((line = br.readLine())!=null)
        {
            String[] split = line.split("=");

            System.out.println(split[0]+"值是:"+split[1]);
        }

        br.close();
    }
}

基本介绍


01:

package FileReaderandFileWritter;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class Properties02 {
    public static void main(String[] args) throws IOException {
        //1.创建Properties对象
        Properties properties = new Properties();

        //2.加载指定配置文件
        properties.load(new FileReader("src\mysql.properties"));

        //3.把K-V显示控制台
        properties.list(System.out);

        //4.根据key,获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("username = "+user);
        System.out.println("passward = "+pwd);

    }
}


02:

package FileReaderandFileWritter;


import java.io.*;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

public class Properties03 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();

        //创建
        //1.如果该文件没有key 就是创建
        //2.如果该文件有key 就是修改

        
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");
        properties.setProperty("pwd","abc111");

//        public synchronized Object setProperty(String key, String value) {
//            return put(key, value);
//        }


//        @Override
//        public synchronized Object put(Object key, Object value) {
//            return map.put(key, value);
//        }

//        public V put(K key, V value) {
//            return putVal(key, value, false);
//        }


//        final V putVal(K key, V value, boolean onlyIfAbsent) {
//            if (key == null || value == null) throw new NullPointerException();
//            int hash = spread(key.hashCode());
//            int binCount = 0;
//            for (ConcurrentHashMap.Node[] tab = table;;) {
//                ConcurrentHashMap.Node f; int n, i, fh; K fk; V fv;
//                if (tab == null || (n = tab.length) == 0)
//                    tab = initTable();
//                else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//                    if (casTabAt(tab, i, null, new ConcurrentHashMap.Node(hash, key, value)))
//                        break;                   // no lock when adding to empty bin
//                }
//                else if ((fh = f.hash) == MOVED)
//                    tab = helpTransfer(tab, f);
//                else if (onlyIfAbsent // check first node without acquiring lock
//                        && fh == hash
//                        && ((fk = f.key) == key || (fk != null && key.equals(fk)))
//                        && (fv = f.val) != null)
//                    return fv;
//                else {
//                    V oldVal = null;
//                    synchronized (f) {
//                        if (tabAt(tab, i) == f) {
//                            if (fh >= 0) {
//                                binCount = 1;
//                                for (ConcurrentHashMap.Node e = f;; ++binCount) {
//                                    K ek;
//                                    if (e.hash == hash &&
//                                            ((ek = e.key) == key ||
//                                                    (ek != null && key.equals(ek)))) {
//                                        oldVal = e.val;
//                                        if (!onlyIfAbsent)
//                                            e.val = value;
//                                        break;
//                                    }
//                                    ConcurrentHashMap.Node pred = e;
//                                    if ((e = e.next) == null) {
//                                        pred.next = new ConcurrentHashMap.Node(hash, key, value);
//                                        break;
//                                    }
//                                }
//                            }
//                            else if (f instanceof ConcurrentHashMap.TreeBin) {
//                                ConcurrentHashMap.Node p;
//                                binCount = 2;
//                                if ((p = ((ConcurrentHashMap.TreeBin)f).putTreeval(hash, key,
//                                        value)) != null) {
//                                    oldVal = p.val;
//                                    if (!onlyIfAbsent)
//                                        p.val = value;
//                                }
//                            }
//                            else if (f instanceof ConcurrentHashMap.ReservationNode)
//                                throw new IllegalStateException("Recursive update");
//                        }
//                    }
//                    if (binCount != 0) {
//                        if (binCount >= TREEIFY_THRESHOLD)
//                            treeifyBin(tab, i);
//                        if (oldVal != null)
//                            return oldVal;
//                        break;
//                    }
//                }
//            }
//            addCount(1L, binCount);
//            return null;
//        }

        //将k-v存储文件即可
        properties.store(new FileOutputStream("src\mysql2.properties"),null);


//        public void store(OutputStream out, String comments)//第2个位置是写解释,没特殊要求写个null
//        throws IOException
//        {
//            store0(new BufferedWriter(new OutputStreamWriter(out, ISO_8859_1.INSTANCE)),
//                    comments,
//                    true);
//        }







    }
}

小作业

01:

package FileHomeWorkDemo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileHomeWork01 {
    public static void main(String[] args) throws IOException {
        String directorPath = "e:\mytemp";
        File file = new File(directorPath);
        if (!file.exists())
        {
            if(file.mkdirs())
            {
                System.out.println("success to create");
            }
            else
            {
                System.out.println("fail to success");
            }

            String filePath = directorPath+"\hello.txt";//e:mytemphello.txt

            file = new File(filePath);

            if (file.isFile())
            {
                if (file.createNewFile())
                {
                    System.out.println("success");

                    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));

                    bufferedWriter.write("hello,world 韩水平牛逼");

                    bufferedWriter.close();
                }
                else {

                    System.out.println("fail");
                }
            }
            else
            {
                System.out.println("file has existed");
            }



        }
    }
}

01:

package FileHomeWorkDemo;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.Properties;

public class HomeWork03 {
    public static void main(String[] args) throws IOException {
        String filePath = "src\dog.properties";

        Properties properties = new Properties();

        properties.load(new FileReader(filePath));

        //properties.list(System.out);

        String name = properties.get("name")+"";
        int age = Integer.parseInt(properties.get("age")+"");

        String color = properties.get("color")+"";

        Dog dog = new Dog(name, age, color);
        System.out.println(dog);

        String serFilePath = "D:\JavaPathExercise\oos.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);

        oos.close();
    }


    //编写一个方法,反序列化dog
    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String serFilePath = "D:\JavaPathExercise\oos.dat";

        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(serFilePath));

        Dog dog = (Dog)objectInputStream.readObject();

        System.out.println(dog);

        objectInputStream.close();
    }
}


class Dog implements Serializable
{
    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;
    }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/336467.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号