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

java 基本IO操作

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

java 基本IO操作

1.JAVA IO
IO指的是输入与输出,Input和Output

java将输入与输出比作流: 流可以理解为是

顺着同一个方向移动的过程,即:流动的概念
输入流:想象为是一个"管道",链接着我们写的java程序与另一端的管道,而流动的方向
       是从另一端移动到我们的程序的过程,是一个获取的过程,操作为"读"
输出流:方向从我们写的程序到另一端的方向,操作为:"写"

java为了规范流的行为,定义了两个超类:
java.io.InputStream和java.io.OutputStream
java.io.InputStream是所有字节输入流的超类(同时是抽象类)
    定义了几个常见的抽象方法:
    int read():读取一个字节
    int read(byte[] data):块读取操作

java.io.OutputStream是所有字节输出流的超类(同时是抽象类)
    void write(int d):写出一个字节
    void write(byte[] data):块写操作

    void write(byte[] data,int off,int len):块写部分数据。

文件流:
java.io.FileInputStream和FileOutputStream
文件流继承自java.io.InputStream和OutputStream
这对流是用来读写文件的流
public class FOSDemo {
    public static void main(String[] args) throws IOException {

        
        //向当前目录下的fos.dat文件中写入数据
        
        FileOutputStream fos = new FileOutputStream("fos.dat");
//        File file = new File("fos.dat");
//        FileOutputStream fos = new FileOutputStream(file);
        

        
        fos.write(-1);
        
        fos.write(2);

        System.out.println("写出完毕!");
        fos.close();

    }
}

文件输入流读取文件数据
public class FISDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("./fos.dat");
        
        
        int d = fis.read();//第一次调用相当于读取文件的第一个字节
        System.out.println(d);//1
        
        d = fis.read();//2
        System.out.println(d);
        
        d = fis.read();
        System.out.println(d);

        fis.close();
    }
}
文件复制
思路:
1:先创建一个文件输入流用于读取原文件
2:再创建一个文件输出流用于将数据抄到复制的文件中
3:顺序的从原文件中读取每一个字节并写入到复制的文件中
public class CopyDemo {
    public static void main(String[] args) throws IOException {
//        FileInputStream fis = new FileInputStream("image.jpg");
//        FileOutputStream fos = new FileOutputStream("image_cp.jpg");

        FileInputStream fis = new FileInputStream("setup.exe");
        FileOutputStream fos = new FileOutputStream("setup_cp.exe");

        
        int d = 0;
        long start = System.currentTimeMillis();
        while((d = fis.read()) != -1) {
            fos.write(d);
        }
        long end = System.currentTimeMillis();
        System.out.println("复制完毕!耗时:"+(end-start)+"ms");
        fis.close();
        fos.close();
    }
}
通过提高每次读写的数据量减少实际读写的次数可以提高读写效率
一组字节一组字节的读写数据称为块读写
public class CopyDemo2 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("setup.exe");
        FileOutputStream fos = new FileOutputStream("setup_cp.exe");

        

        byte[] data = new byte[1024*10];//10kb
        int len;//记录每次实际读取到的字节数
        //16:45回来
        long start = System.currentTimeMillis();
        while( (len = fis.read(data)) != -1 ){
            fos.write(data,0,len);
        }
        long end = System.currentTimeMillis();
        System.out.println("复制完毕,耗时:"+(end-start)+"ms");

        fis.close();
        fos.close();
    }
}
向文件中写入文本数据
public class WriteStringDemo {
    public static void main(String[] args) throws IOException {
        
        FileOutputStream fos = new FileOutputStream("demo.txt",true);
        
        String line = "一给窝里giao~~";
        byte[] data = line.getBytes(StandardCharsets.UTF_8);
        fos.write(data);

//        String line1 = "我太难了~~~";
//        byte[] data1 = line1.getBytes(StandardCharsets.UTF_8);
//        fos.write(data1);
//
//        String line2 = "嘿嘿嘿~";
//        byte[] data2 = line2.getBytes(StandardCharsets.UTF_8);
//        fos.write(data2);


        System.out.println("写出完毕!");
        fos.close();

    }
}
读取文件中的文本数据
public class ReadStringDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("demo.txt");
        //将demo.txt文件中所有数据读取回来
        FileInputStream fis = new FileInputStream(file);
        long len = file.length();//获取文件的大小,单位字节
        byte[] data = new byte[(int)len];//常见与文件大小一致的字节数组
        fis.read(data);//块读,将文件所有字节读到data数组中
        
        String line = new String(data, StandardCharsets.UTF_8);
        System.out.println(line);
        fis.close();
    }
}
JAVA将流分为了两类:节点流与处理流
节点流:又称为低级流,是实际链接程序与另一端的"管道",负责实际读写数据的流。
      读写一定是建立在低级流的基础上进行的。
处理流:又称为高级流,不能独立存在,必须链接在其它流上,目的是当数据流经当前
      流时对数据进行某种加工处理,简化我们相应的操作。
实际开发中,我们总是会串联一组高级流到一个低级流上,以流水线式的加工处理完成
读写的操作,这个过程也成为"流的链接"

缓冲流:
java.io.BufferedInputStream和BufferedOutputStream
它们同样继承自InputStream和OutputStream

缓冲流的功能是提高读写效率。
public class CopyDemo3 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("setup.exe");
        BufferedInputStream bis = new BufferedInputStream(fis);

        FileOutputStream fos = new FileOutputStream("setup_cp.exe");
        //缓冲流内部缓冲区默认为8kb
//        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //重载的构造器可以自行指定缓冲区大小
        BufferedOutputStream bos = new BufferedOutputStream(fos,1024*10);
        int d = 0;
        long start = System.currentTimeMillis();
        while((d = bis.read()) != -1) {
            bos.write(d);
        }
        long end = System.currentTimeMillis();
        System.out.println("复制完毕!耗时:"+(end-start)+"ms");
        bis.close();
        bos.close();
    }
}
缓冲输出流写出数据的缓冲区问题
public class FlushDemo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("bos.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        String line = "该配合你演出的我演视而不见。";
        byte[] data = line.getBytes(StandardCharsets.UTF_8);
        bos.write(data);
        System.out.println("写出完毕");
        
//        bos.flush();//冲
        bos.close();

    }
}
标准的JAVA BEAN规则
应当有无参构造器
属性应当有对应的get,set方法

Person : 人

使用当前类的实例测试对象流的序列化与反序列化操作
序列化:将一个对象按照其结构转化为一组字节的过程
反序列化:将一组字节还原为一个对象的过程
public class Person implements Serializable {
    
    public static final long serialVersionUID = 1L;
    private String name;//名字
    private int age;//年龄
    private String gender;//性别
    
    private transient String[] otherInfo;//其它信息

//    private int salary;

    public Person(){}

    public Person(String name, int age, String gender, String[] otherInfo) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.otherInfo = otherInfo;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String[] getOtherInfo() {
        return otherInfo;
    }

    public void setOtherInfo(String[] otherInfo) {
        this.otherInfo = otherInfo;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                ", gender='" + gender + ''' +
                ", otherInfo=" + Arrays.toString(otherInfo) +
                '}';
    }
}
对象流java.io.ObjectOutputStream和ObjectInputStream
对象流是一对高级流,功能是进行对象序列化与反序列化。方便我们读写java对象
public class OOSDemo {
    public static void main(String[] args) throws IOException {
        //将一个Person对象写入文件保存
        String name = "苍老师";
        int age = 18;
        String gender = "女";
        String[] otherInfo = {"身高168","是个演员","来自日本","88,90","是我们的启蒙老师"};
        Person p = new Person(name,age,gender,otherInfo);
        FileOutputStream fos = new FileOutputStream("person.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        
        oos.writeObject(p);

        System.out.println("写出完毕!");
        oos.close();

    }
}
使用对象输入流反序列化对象
public class OISDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("person.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        Person person = (Person)ois.readObject();
        
//        System.out.println(ois.readObject());
        System.out.println(person);

        ois.close();

    }
}
JAVA将流按照读写单位划分为字节流与字符流
 java.io.InputStream和OutputStream是所有字节输入流与输出流的超类

 java.io.Reader和Writer则是所有字符输入流与输出流的超类

 InputStream和OutputStream 与 Reader和Writer 是平级关系,相互不存在继承关系

 字符流里也同样定义了对应的读取和写出方法,只是单位都以字符为最小单位读写。


 转换流
 java.io.InputStreamReader和OutputStreamWriter
 它们是常用的字符流的一对实现类,同时它们也是一对高级流。
 它在流连接中的作用2个:
 1:衔接字节流与字符流
 2:将字节与字符进行转换方便读写。
public class OSWDemo {
    public static void main(String[] args) throws IOException {
        //向文件osw.txt中写入字符串
        FileOutputStream fos = new FileOutputStream("osw.txt");
        
        OutputStreamWriter osw = new OutputStreamWriter(
                fos,StandardCharsets.UTF_8);

        //转换流会将写出的字符串转换为字节后再通过链接的文件流写入文件。
        osw.write("摩擦摩擦~在光滑的马路牙子上打出溜滑~");
        osw.write("我的滑板鞋~时尚时尚最时尚~");
        System.out.println("写出完毕!");
        osw.close();
    }
}
转换输入流测试字符流读取字符的操作
public class ISRDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("osw.txt");
        InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
        
//        int d = isr.read();
        
        int d;
        while((d = isr.read())!=-1) {
            System.out.print((char) d);
        }
        isr.close();

    }
}
缓冲字符流
 java.io.BufferedWriter和BufferedReader
 缓冲字符流是一对高级流,且是一对字符流。
 功能:块写文本数据加速

 java.io.PrintWriter
 具有自动行刷新的缓冲字符输出流
public class PWDemo {
    public static void main(String[] args) throws FileNotFoundException {
        //向文件pw.txt中写入文本数据
        PrintWriter pw = new PrintWriter("pw.txt");
        pw.println("super idol的笑容都没你的甜。");
        pw.println("八月正午的阳光都没你耀眼。");
        System.out.println("写出完毕!");
        pw.close();

    }
}
在流连接中使用PrintWriter
public class PWDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        //如果希望有追加模式,则需要自行创建文件输出流并指定
        FileOutputStream fos = new FileOutputStream("pw.txt",true);
        //在转换流上加上字符集,可以按照指定字符集写出。
        OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
        BufferedWriter bw = new BufferedWriter(osw);
        
        PrintWriter pw = new PrintWriter(bw,true);

//        FileOutputStream fos = new FileOutputStream("pw.txt",true);
//        BufferedOutputStream bw = new BufferedOutputStream(osw);
        
//        PrintWriter pw = new PrintWriter(bw);

        Scanner scanner = new Scanner(System.in);
        while(true) {
            String line = scanner.nextLine();
            if("exit".equalsIgnoreCase(line)){
                break;
            }
            pw.println(line);
        }
        System.out.println("写出完毕!");

        pw.close();

    }
}
使用缓冲字符输入流java.io.BufferedReader读取文本数据
 缓冲字符输入流是一个高级流,有两个主要功能:
 1:块读文本数据加速
 2:可以按行读取字符串
public class BRDemo {
    public static void main(String[] args) throws IOException {
        //将当前源代码输出到控制台上
        FileInputStream fis = new FileInputStream("./src/io/BRDemo.java");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br  = new BufferedReader(isr);
        String line;
        
        while((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
}

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

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

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