Java Io流知识详解

作者: singworld 分类: Java 发布时间: 2019-04-23 16:37

对象序列化

将序列号对象写入文件

public class Foo implements Serializable {
    private int width;
    private  int height;
    // transient String userName 不会被序列化

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}
public class JavaIo {
    public static void main(String[] args) {
        Foo myFoo = new  Foo();
        myFoo.setWidth(37);
        myFoo.setHeight(70);

        try {
            FileOutputStream fs = new FileOutputStream("foo.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(myFoo);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

解序列化

            FileInputStream fileInputStream = new FileInputStream("foo.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Object one = objectInputStream.readObject();

将字符串写入文本文件

        try {
            FileWriter fileWriter = new FileWriter("foo.txt");
            fileWriter.write("helloworld");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

文件操作

        File file = new File("Mycode.txt");
        //创建新的目录
        File dir = new File("Chapter7");
        dir.mkdir();
        //列出目录下的所有内容
        if (dir.isDirectory()){
            String[] dirContents = dir.list();
            for (int i = 0; i < dirContents.length; i++) {
                String dirContent = dirContents[i];
                System.out.println("==="+dirContent);

            }
            //取得文件绝对路径
            System.out.println(dir.getAbsolutePath());
            // 删除文件或目录
            boolean isDeleted = file.delete();

        }

缓冲区

            File file = new File("foo.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
            }
            bufferedReader.close();

Leave a Reply

Your email address will not be published. Required fields are marked *