JAVA输入输出

JAVA程序访问外部数据,需要实现对数据的传送,为此JAVA提供了庞大的IO类库支持。I就是输入,input,指数据从外部读取到程序中;O就是输出,output,指数据从程序写出到外部文件中。
下面介绍一些常用的类:

  • File类
  • InputStream、OutputSream字节输入输出流
  • Reader、Writer字符输入输出流
  • DataInputStream、DataOutputSteam二进制流读写二进制文件
  • ObjectInputStream、ObjectOutputStream序列化对象

File类

File类实现对文件的基本操作,该类主要用于文件和目录的创建、文件的查找和文件的删除等。
File对象代表磁盘中实际存在的文件和目录。
示例:

        File file = new File("/Users/jason/Desktop/mywork.txt");//创建File对象
        file.createNewFile();  //创建文件
        System.out.println(file.exists());  //文件是否存在
        System.out.println(file.isFile());  //是不是文件
        System.out.println(file.isDirectory()); //是不是目录
        System.out.println(file.getName());  //文件名
        System.out.println(file.getPath());  //文件相对路径
        System.out.println(file.getAbsolutePath());  //文件绝对路径
        System.out.println(file.length());  //文件大小,单位字节
        file.delete();   //删除文件

数据流是一串连续不断的数据的集合,java中将输入输出抽象称为流,流是一个很形象的概念,就好像水管,将两个容器连接起来。将数据从外部读取到程序中的称为输入流,将数据从程序写到外部的称为输出流。


stream.png

InputStream、OutputSream字节输入输出流

字节流是按字节,一个字节一个字节的读取或写入数据。基本单位是8bit的通用字节。InputStream和OutputStream是字节流的基类,他们是抽象类。常用的是他们的子类FileInputStream和FileOutputStream。

InputStream(抽象类)常用方法 说明
int read() 从输入流中读取下一个字节数据并返回
int read(byte[ ] b) 从输入流中读取数据,存储在数组b中,返回实际读取到的字节数
int read(byte[ ] b,int off,int len) 从输入流中读取最多len长度的字节,存储在数组b中,保存位置从off开始,返回读取到的字节数
void close() 关闭输入流
OutputStream(抽象类)常用方法 说明
void write(int c) 把指定字节写入输出流
void write(byte[ ] b) 把数组b中的所有字节写入输出流
void write(byte[ ] b,int off,int len) 把数组中从偏移量off开始的长度为len的字节写入输出流
void close() 关闭输出流

示例:

public class Test {
    public static void main(String[] args) {
        FileInputStream fis = null;//创建输入流对象
        FileOutputStream fos = null;//创建输出流对象
        try {
            //给输入输出流传路径
            fis = new FileInputStream("hello.txt");
            fos = new FileOutputStream("test.txt",true);//true表示写入的文件是追加,false表示覆盖
            byte[] words = new byte[1024];
            int len = -1;
            while((len = fis.read(words)) != -1){//循环读取,保存到数组中
                fos.write(words,0,len);//写入文件
            }
            System.out.println("文件复制完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fos.close();  //流先打开的后关,后打开的先关
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Reader、Writer字符输入输出流

字符流是按字符,一个字符一个字符的读取或写入数据。基本单位是16bit的Unicode字符。Reader和Writer是字符流的基类,他们是抽象类。常用的是他们的子类FileReader、FileWriter、BufferedReader、BufferedWriter。

Reader(抽象类)常用方法 说明
int read() 从输入流中读取单个字符,返回读到的字符
int read(char[ ] b) 从输入流中读取b.length个字符,存储在数组b中,返回实际读取到的字符数
int read(char[ ] b,int off,int len) 从输入流中读取最多len长度的字符,存储在数组b中,保存位置从off开始,返回读取到的字符数
void close() 关闭输入流
InputStream(抽象类)常用方法 说明
void write(String str) 把指定字符串str中的字符写入输出流
void write(String str,int off,int len) 把字符串str从off开始的长度为len的多个字符写入输出流
void flush() 刷新输出流
void close() 关闭输出流

示例:

public class Test {
    public static void main(String[] args) {
            FileInputStream fis = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            FileWriter fw = null;
            BufferedWriter bw = null; //带缓冲区的字符流,先读写在缓冲区,效率更高
            try {
                fis = new FileInputStream("test1.txt");
                isr = new InputStreamReader(fis,"UTF-8");//指定输入流的编码格式
                br = new BufferedReader(isr);
                String str = null;
                StringBuffer sb = new StringBuffer();
                while((str = br.readLine()) != null){//按行读取数据
                    sb.append(str);//追加字符串
                }
                String newStr = sb.toString();
                fw = new FileWriter("test2.txt", true);//追加写入文件
                bw = new BufferedWriter(fw);
                bw.write(newStr);//写入文件
                bw.newLine();//写入空行
                bw.flush();//强制清空缓冲区
                System.out.println("copy successful");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {//关闭流
                    bw.close();
                    fw.close();
                    br.close();
                    isr.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
}

DataInputStream、DataOutputSteam二进制流读写二进制文件

用二进制流读写二进制文件,用法和字节流相似。
示例:

public class Test {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        try {//创建二进制流
            fis = new FileInputStream("file.class");
            dis = new DataInputStream(fis);
            fos = new FileOutputStream("filecopy.class");
            dos = new DataOutputStream(fos);
            int temp;
            while((temp = dis.read())!=-1){//读取信息保存到temp中
                dos.write(temp); //把temp中的信息写入文件
            }
            System.out.println("copy class file  done");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {//关闭流
                dos.close();
                fos.close();
                dis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

ObjectInputStream、ObjectOutputStream序列化对象

序列化就是把对象的状态存储到特定介质中的过程,也就是把对象状态转换为可传输格式的过程。简单来说就是把对象数据二进制化。
JAVA中只有实现了java.io.Serializable接口的类的对象才可以被序列化。
示例:

public class Test {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        try {  //创建序列化对象
            oos = new ObjectOutputStream(new FileOutputStream("stuInfo.txt"));
            Student stu = new Student("安妮",18);
          oos.writeObject(stu);  // 写入文件
            System.out.println("write stuList info to file done");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(oos!=null){
                try {
                    oos.close(); //关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Java输入输出流(一)# Android 是基于 Java 语言编写的,在安卓程序的很多时候会用到有关 I/O ...
    梁加盐阅读 1,522评论 0 4
  • tags:io categories:总结 date: 2017-03-28 22:49:50 不仅仅在JAVA领...
    行径行阅读 2,300评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,551评论 19 139
  • 没有高素质的教师队伍,一切高质量的教育计划都是空谈。本学期钟英小学教师队伍又壮大啦,加入了23位新成员,为迅...
    Hi_Myra阅读 577评论 0 0
  • 如果你在大城市,能和外国人交流肯定不是什么新鲜事儿了,但是能真正和外国人聊很多有意思的话题,并且听他们讲在中国遇到...
    5b898d2cdc00阅读 1,191评论 4 2

友情链接更多精彩内容