JAVA输入输出

来源:互联网 发布:电子信息工程 软件方向 编辑:程序博客网 时间:2024/06/09 20:50

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

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