Java 中 I/O流使用

版权声明:最短的时间最核心的知识,有疑问,欢迎进行留言。 https://blog.csdn.net/lizhidefengzi/article/details/79357132

1.I/O流

1.1 基本概念

I/O就是Input/Output的简写形式,也就是输入/输出,换句话说就是指读写操作。
I/O流就是指像流水一样源源不断读写的操作。

1.2 基本分类

按照读写单位/单元的不同分为:字节流 和 字符流。
其中字节流就是指以字节(byte)为单位进行读写的流,可以用于读写任何文件。
其中字符流就是指以字符(2个字节)为单位进行读写的流,只能用于读写文本文件。

按照数据流动方向的不同分为:输入流 和 输出流(站在程序的角度来看)。
其中输入流就是指从文件中读取数据并输入到程序中,也就是读文件。
其中输出流就是指将程序中的数据输出到文件中,也就是写文件。

1.3 IO流的层次结构

字节流的顶层类为:InputStream类 和 OutputStream类.
其中InputStream类主要子类:FileInputStream、DataInputStream、ObjectInputStream
其中OutputStream类主要子类:FileOutputStream、DataOutputStream(间接子类)、 ObjectOutputStream

字符流的顶层类为:Reader类 和 Writer类.
其中Reader类主要子类:BufferedReader、InputStreamReader、StringReader。
其中Writer类主要子类:BufferedWriter、OutputStreamWriter、StringWriter。

文件拷贝

package homework;

import java.io.*;

public class TestFileCopy {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try{
            FileInputStream fis=new FileInputStream("D:/a.txt");
            FileOutputStream fos=new FileOutputStream("D:/b.txt");

            /*int res=0;
            while((res=fis.read())!=-1){
                fos.write(res);     
            }*/


            //有可能会耗尽内存空间
            /*byte[] data=new byte[fis.available()];
            int res=fis.read(data);
            fos.write(data);
            */

            byte[] data=new byte[1024*8];
            int res=0;
            while((res=fis.read(data))!=-1){
                fos.write(data,0,res);
            }


            fis.close();
            fos.close();

        }catch(Exception e)
        {
            e.printStackTrace();
        }


    }

}

2.TestFileOutputStream

package homework;

import java.io.FileOutputStream;

public class TestFileOutputStream {

    public static void main(String[] args) {

        try{
            FileOutputStream fos=new FileOutputStream("D:/a.txt",true);
            fos.write(97);
            fos.write("hello".getBytes());
            fos.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

3.TestDataInputStream

package homework;

import java.io.*;

public class TestDataInputStream {

    public static void main(String[] args) {

        try{
            DataInputStream dis=new DataInputStream(new FileInputStream("D:/a.txt"));

            int res=dis.readInt();
            System.out.println("从文件中读取到的整数是:"+res);
            dis.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

4.递归打印目录文件 – 深度递归

package homework;
import java.io.File;

public class TestDirPrint {

    public static void printDir(File f){
        //递归打印目录文件   -- 深度递归

        if(f.isDirectory()){
            System.out.println("["+f.getName()+"]");
            File[] ff=f.listFiles();

            for(File f1:ff){
                printDir(f1);
            }
        }
        if(f.isFile()){
            //printDir(f);
            System.out.println(f.getName());
        }       
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        File f=new File("D:\\Java\\课件\\JAVASE核心阶段\\7IO流的详细讲解-课件-v1\\day17资料");
        TestDirPrint.printDir(f);

    }

}

5.TestPrintStream

package homework;

import java.io.*;

public class TestPrintStream {

    public static void main(String[] args) {
        try{
            //1.创建PrintStream 类型的对象与指定的文件关联
            PrintStream ps=new PrintStream(new FileOutputStream("D:/b.txt"));
            ps.println("hello");
            ps.close();

            //2.向输出流中写入字符串“hello”
            //3.关闭流对象并释放相关的资源
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

5.创建BufferedReader类型的对象与指定的文件关联

package homework;

import java.io.*;

public class TestBufferedReader {

    public static void main(String[] args) {

        try{
            //1.创建BufferedReader类型的对象与指定的文件关联       
            BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("D:/a.txt")));
            //2.读取文件中的内容并打印出来
            String str=br.readLine();
            br.close();
            //3.关闭流对象并释放资源
        }catch(Exception e){
            e.printStackTrace();    
        }
    }

}

6.TestChatMsg

package homework;
import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.Calendar;

public class TestChatMsg {

    public static void main(String[] args) {
        try{
        //1.创建BufferedReader类型的对象,用于建立到键盘输(System.in)入的通道
        //构造方法需要Reader类型对的引用  System.in是InputStream类型的引用
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        //2.创建PrintStream类型的对象,用于建立c:/a.txt文件的通道    
        PrintStream ps=new PrintStream(new FileOutputStream("D:/b.txt"));
        //3.不断地提示用户输入要发送的内容并写入到文件
        boolean flag=true;
        while(true){
            System.out.println((flag?"张三":"李四")+"请输入要发送的内容:");
            String str=br.readLine();
            if("bye".equalsIgnoreCase(str))break;
            //每次向文件中写入聊天记录时,获取当前系统时间

            Calendar c=Calendar.getInstance();
            java.util.Date d1=c.getTime();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ps.println(sdf.format(d1)+(flag?"张三说:":"李四说: ")+str);
            flag=!flag;

        }
        //4.直到用户输入的内容为"Bye"时,结束循环
        //5.关闭流对象并释放相关的资源

        ps.close();
        br.close();
        }catch(Exception e){
            e.printStackTrace();
        }       

    }

}

ObjectInputStream
ObjectOutputStream
User

package xdl.day18;



public class User implements java.io.Serializable{
    private String userName;//用于描述用户名信息
    private String passWord;//用于描述密码信息
    private String email;   //用于描述邮箱信息
    public User(String userName, String passWord, String email) {
        super();
        setUserName(userName);
        setPassWord(passWord);
        setEmail(email);
    }
    public User() {
        super();
    }
    @Override
    public String toString() {
        return "User [userName=" + userName + ", passWord=" + passWord + ", email=" + email + "]";
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

ObjectInputStream

package xdl.day18;

import java.io.*;

public class TestObjectInputStream {

    public static void main(String[] args) {



        try{
        //1.创建ObjectInputStream类型的对象,与指定的文件关联
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:/a.txt"));
        //2.读取文件中的User对象并使用变量记录,最后打印出来
        Object obj=ois.readObject();
        if(obj instanceof User){
            User u=(User)obj;
            System.out.println(u);
        }
        //3.关闭流对象并释放相关的资源
        ois.close();
    }catch(Exception e){
        e.printStackTrace();
        }
    }

}

ObjectOutputStream

package xdl.day18;

import java.io.*;

public class TestObjectOutputStream {

    public static void main(String[] args) {

        try{
        //1.创建ObjectOutputStream类型对象,于指定的文件关联
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:/a.txt"));
        //2.创建User类型对象,并进行初始化
        User u=new User("xiaomage","123456","[email protected]");
        //3.将User类型的对象整体写入到文件中
        oos.writeObject(u);
        System.out.println("数据写入成功!");
        //4.关闭流并释放相关的资源
        oos.close();
    }catch(Exception e){
        e.printStackTrace();
    }
    }

}

猜你喜欢

转载自blog.csdn.net/lizhidefengzi/article/details/79357132
今日推荐