IO流编程

IO编程

静听花开花落,坐看云卷云舒

一切属于IO流都要进行关闭操作

1. File文件操作

文件的分隔符:File.separator;

File文件操作的方法
方法类型说明
public File(String pathName)构造操作文件的完整路径
public File(File parent,String child)构造操作文件的父路径和文件的名称
public boolean createNewFile() throws Exception普通创建文件
public boolean delete()普通删除文件
public boolean exists()普通文件是否存在
public File getParentFile()普通找到文件的父路径
public boolean mkdirs()普通创建指定路径
public boolean canRead()普通文件是否可读
public boolean canWrite()普通文件是否可写
public boolean canExecute()普通文件是否可执行
public long length()普通获取文件大小(字节)
public boolean isDirectory()普通是否是目录
public boolean isFile()普通是否是文件
public boolean isHidden()普通是否隐藏
public File[] listFiles()普通列出目录中的全部文件信息
  • 栗子1:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class File1 {
    public static double round(double num,int scale) {
        return Math.round(Math.pow(10,scale) * num) / Math.pow(10,scale);
    }
    public static void main(String[] args) throws Exception {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {
            System.out.println("文件是否可读:" + file.canRead());
            System.out.println("文件是否可写:" + file.canWrite());
            System.out.println("文件是否可执行:" + file.canExecute());
            System.out.println("文件大小:" + File1.round(file.length() / (double)1024 / 1024,2) + "M");
            System.out.println("最后的修改时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
            System.out.println("是目录:" + file.isDirectory());
            System.out.println("是文件:" + file.isFile());
            System.out.println("是否隐藏" + file.isHidden());
            file.delete();
            System.out.println("文件删除成功!");
        } else {
            file.createNewFile();
            System.out.println("文件创建成功");
            System.out.println("文件是否可读:" + file.canRead());
            System.out.println("文件是否可写:" + file.canWrite());
            System.out.println("文件是否可执行:" + file.canExecute());
            System.out.println("文件大小:" + File1.round(file.length() / (double)1024 / 1024,2) + "M");
            System.out.println("最后的修改时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
            System.out.println("是目录:" + file.isDirectory());
            System.out.println("是文件:" + file.isFile());
            System.out.println("是否隐藏" + file.isHidden());
        }
    }

}

  • 栗子2:
import java.io.File;

public class File2 {
    public static void main(String[] args) {
        File file = new File("D:" + File.separator + "test");
        listDir(file);

    }

    private static void listDir(File file) {
        //目录进行遍历,文件进行重命名
        if (file.isDirectory()) {
            File result[] = file.listFiles();
            if (result != null) {
                for (int i = 0; i < result.length; i++) {
                    System.out.println(result[i]);
                }
            }
        } else {
            if (file.isFile()) {
                String fileName = null;
                if (file.getName().endsWith(".txt")) {
                    fileName = file.getName().substring(0,file.getName().lastIndexOf(".")) + ".java";
                    File newFile  = new File(file.getParentFile(),fileName);
                    file.renameTo(newFile);
                }
            }
        }
    }
}

2. 字节输出流(OutputStream)

程序需要读取数据(读)时,利用输入流完成,程序需要将数据保存到数据(写)时,需要输出流

public abstract class OutputStream extends Object implements Closeable, Flushable {}
  • Closeable接口
public interface Closeable extends AutoCloseable {
    void close() throws IOException;
}
  • Flushable接口
public interface Flushable {
    void flush() throws IOException;
}
OutputStream类的常用方法
方法类型说明
public abstract void write(int b) throws IOException普通输出单个字节数据
public void write(byte[] b) throws IOException普通输出一组字节数据
public void write(byte[] b,int off,int len) throws IOException普通输出部分字节数据
public void close() throws IOException普通关闭输出流
public void flush() throws IOException普通刷新缓冲区
FileOutputStream类的常用方法

主要目的为OutputStream父类实例化

方法类型说明
public FileOutputStream(File file) throws FileNotFoundException构造采用覆盖的形式创建文件输出流
public FileOutputStream(File file,boolean append) throws FileNotFoundException构造采用覆盖或者追加的形式创建文件输出流
  • 栗子:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;


public class OutputStream1 {
    public static void main(String[] args) throws Exception {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
       if (!file.getParentFile().exists()) {
           file.getParentFile().mkdirs();
       }
        OutputStream output = new FileOutputStream(file,true);
       String str = "hdhf\r\n";
       output.write(str.getBytes());
       output.flush();
       output.close();
    }
}

3. 字节输入流(InputStream)

程序读取的时候需要输入

public abstract class InputStream extends Object implements Closeable {}
InputStream类的常用方法
方法类型说明
public abstract int read throws IOException普通读取单个字节数据,如果现在已经读取到底了,返回-1
public int read(byte[] var1) throws IOException普通读取一组字节数据,返回的是读取的个数;如果没有数据,且已经读取到底则返回-1
public int read(byte[] var1, int var2, int var3) throws IOException普通读取一组字节数据,只占数组的部分
public void close() throws IOException普通关闭输入流
public byte[] readAllBytes() throws IOException普通读取输入流的全部字节数据,jdk1.9后新增
public long transferTo(OutputStream out) throws IOException普通输入流转存到输出流,jdk1.9后新增

栗子:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InputStream1 {
    public static void main(String[] args) throws Exception {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
        if (file.exists()) {
            InputStream input = new FileInputStream(file);
            byte[] data = new byte [1024];
            int len = input.read(data);
           /* byte data [] = input.readAllBytes();*///jdk1.9后新增
            System.out.println(new String(data,0,data.length));
            input.close();
        }
    }
}

4. 字符输出流(Writer)

方便中文的输出和写入

public abstract class Writer implements Appendable, Closeable, Flushable{}
  • Appendable接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package java.lang;

import java.io.IOException;

public interface Appendable {
    Appendable append(CharSequence var1) throws IOException;

    Appendable append(CharSequence var1, int var2, int var3) throws IOException;

    Appendable append(char var1) throws IOException;
}

Writer类的常用方法
方法类型说明
public void write(int var1) throws IOException普通输出单个字符
public void write(char[] var1) throws IOException普通输出字符数组
public void write(String var1) throws IOException普通输出字符串
public Writer append(CharSequence var1) throws IOException普通追加输出内容
public abstract void flush() throws IOException普通刷新缓冲区
public abstract void close() throws IOException普通关闭输出流
FileWriter类的常用方法
方法类型说明
public FileWriter(File var1) throws IOException普通采用覆盖的形式创建文件输出流
public FileWriter(File var1, boolean var2) throws IOException普通采用覆盖或追加的形式创建文件输出流
  • 栗子:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Writer1 {
    public static void main(String[] args) throws IOException {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Writer out = new FileWriter(file);
        out.write("dhhd");
        out.append("djhfhh");
        out.flush();//特别注意,没有也能输出是因为close()强制刷新
        out.close();
    }
}

5. 字符输入流(Reader)

方便中文的输入和读

public abstract class Reader implements Readable, Closeable {}
  • Readable接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package java.lang;

import java.io.IOException;
import java.nio.CharBuffer;

public interface Readable {
    int read(CharBuffer var1) throws IOException;
}

Reader类的常用方法
方法类型说明
public int read() throws IOException普通读取单个字符,无数据读取时返回-1
public int read(char[] var1) throws IOException普通读取多个字符,并且返回读取个数
public long skip(long var1) throws IOException普通跳过指定的字符个数后读取
public boolean ready() throws IOException普通是否可以开始读取数据
public abstract void close() throws IOException普通关闭输入流
  • 栗子
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

public class Reader1 {
    public static void main(String[] args) throws Exception {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
        if (file.exists()) {
            Reader reader = new FileReader(file);
            char[] data = new char[1024];
            reader.skip(2);
            int len = reader.read(data);
            System.out.println(new String(data,0,len));
            reader.close();
        }
    }
}

6. 字节流与字符流区别,转换流

字节流直接进行数据处理操作,字符流使用了缓冲区

  • 转换流栗子:
import java.io.*;


public class OutputStream1 {
    public static void main(String[] args) throws Exception {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
       if (!file.getParentFile().exists()) {
           file.getParentFile().mkdirs();
       }
        OutputStream output = new FileOutputStream(file,true);
        Writer out = new OutputStreamWriter(output);
      /* String str = "hdhf\r\n";
       output.write(str.getBytes());*/
      out.append("djhhbdfhl");
       output.flush();
       out.flush();
        output.close();
        out.close();
    }
}

7. 内存操作流

一般用于BIO

字节内存操作流:ByteArrayInputStream,ByteArrayOutputStream

  • ByteArrayInputStream类
public class ByteArrayInputStream extends InputStream {}
  • ByteArrayOutputStream
public class ByteArrayOutputStream extends OutputStream {}

字符内存操作流:CharArrayReader,CharArrayWriter

  • CharArrayReader
public class CharArrayReader extends Reader {}
  • CharArrayWriter
public class CharArrayWriter extends Writer {}

8. 管道流

一般用于NIO

管道输出流:PipedOutputStream,PipedWriter

  • PipedOutputStream
public class PipedOutputStream extends OutputStream {}
  • PipedWriter
public class PipedWriter extends Writer {}

管道输入流:PipedInputStream,PipedReader

  • PipedInputStream
public class PipedInputStream extends InputStream {}
  • PipedReader
public class PipedReader extends Reader {}

9. 打印流

解决字节和字符输出流的局限性

public class PrintWriter extends Writer {}
  • 栗子:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class PrintWriter1 {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D:" + File.separator + "test" + File.separator + "t.txt");
        PrintWriter pu = new PrintWriter(new FileOutputStream(file));
        pu.println("姓名:djhj");
        pu.print("年龄:");
        pu.print(15);
        pu.close();
    }
}

10. 缓冲输入流(BufferedReader)

字符流的缓冲区数据读取

BufferedReader类的常用方法
方法类型说明
public BufferedReader(Reader var1)构造接受一个Reader类的实例
public String readLine() throws IOException普通一次性从缓冲区中将内容全部读取进来
  • 栗子
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReader1 {
    public static void main(String[] args) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请输入您的年龄:");
        String msg = input.readLine();
        if (msg.matches("\\d{1,3}")) {
            int age = Integer.parseInt(msg);
            System.out.println("年龄为:" + age);
        } else {
            System.out.println("输入的不是数字");
        }

        input.close();
    }
}

11. 对象序列化

把一个对象变为二进制的数据流的方法,必须实现Serializable接口,不能序列化关键字 transient

ObjectOutputStream类的常用方法
方法类型说明
public ObjectOutputStream(OutputStream var1) throws IOException构造传入输入的对象
public final void writeObject(Object var1) throws IOException普通输出对象
ObjectInputStream类的常用方法
方法类型说明
public ObjectInputStream(InputStream var1) throws IOException构造构造输入对象
public final Object readObject() throws IOException, ClassNotFoundException {普通从指定位置读取对象
  • 栗子
import java.io.Serializable;

@SuppressWarnings("serial") //序列化编号自动生成
public class Member implements Serializable {
    private transient String memberId;//不能被序列化
    private String name;
    private int age;

    public Member(String memberId, String name, int age) {
        this.memberId = memberId;
        this.name = name;
        this.age = age;
    }

    public String getMemberId() {
        return memberId;
    }

    public void setMemberId(String memberId) {
        this.memberId = memberId;
    }

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

    @Override
    public String toString() {
        return "Member{" +
                "memberId='" + memberId + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  • 对象序列化与反序列化
import java.io.*;

public class JavaIODemo {
    private static final File SAVE_FILE = new File("D:" + File.separator + "test" + File.separator + "t.txt");

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        savaObject(new Member("11","lisi",99));
        System.out.println(loadObject());
    }
    //序列化
    private static void savaObject(Member lisi) throws IOException {
        ObjectOutputStream oos  = new ObjectOutputStream(new FileOutputStream(SAVE_FILE));
        oos.writeObject(lisi);
        oos.close();
    }
    //反序列化
    private static Object loadObject() throws IOException, ClassNotFoundException {
        ObjectInputStream ois  = new ObjectInputStream(new FileInputStream(SAVE_FILE));
        Object obj = ois.readObject();
        ois.close();
        return obj;
    }
}

12. 总结

总结了一些IO编程,还有一些没有在里面,欢迎在评论总结!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值