Java IO beginner

javaIO Programming

IO system

avatar

File

Common method Explanation
mkdir Create a single directory
mkdirs Creating multiple directories
getPath Get path to the file
length Get the length of the file
getName Get file name
getParentFile Get up a directory file
exists Determine whether a file exists
createNewFile Create a file
list Returns an array of strings naming files in the directory and directory
listFiles Returns an array of abstract pathnames indicates that the file directory by this abstract pathname represented
getAbsolutePath Returns the absolute pathname of this abstract pathname string

Create a file

Create a single file
@Test
    //文件的创建
    public void IoFilePractise() throws IOException {
        File file = new File("D:\\file\\1.txt");
        //判断file目录是否存在
        if (!file.getParentFile().exists()) {
            System.out.println("D:\\file目录不存在,立刻创建该目录");
            file.getParentFile().mkdir();
        }
        //判断1.txt文件是否存在
        if (!file.exists()) {
            System.out.println("1.txt文件不存在,立刻创建该文件");
            file.createNewFile();
        }
    }
复制代码
Multi-level file creation
@Test
    public void IoFilePractise3() throws IOException {
        File file=new File("D:\\file\\B\\B1\\B2\\rose.txt");
        //创建多个层级目录
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //创建rose.txt文件
        if(!file.exists()){
            file.createNewFile();
        }
    }
复制代码

Delete files

Delete the specified files and directories, it is worth noting that, if only to delete the specified directory, the directory there are other files or directories, then there is no way to delete success

@Test
    public void IoFilePractise1() throws IOException {
        File file = new File("D:\\file\\A\\jack.txt");
        //在上一个例子的基础上,创建A目录和jack.txt文件
        file.getParentFile().mkdir();
        file.createNewFile();
        //尝试直接删除A目录
        file.getParentFile().delete();
        //判断是否删除A目录成功
        if (file.getParentFile().exists()) {
            System.out.println("A目录没有被删除");
        } else {
            System.out.println("删除A目录成功");
        }
    }
复制代码
@Test
    //根据上面的为基础
    public void IoFilePractise2() {
        File file = new File("D:\\file\\A\\jack.txt");
        file.delete();
        file.getParentFile().delete();
        //判断是否删除A目录成功
        if (file.getParentFile().exists()) {
            System.out.println("A目录没有被删除");
        } else {
            System.out.println("删除A目录成功");
        }
    }
复制代码

Output file directory

Number of all files and output statistics D drive following names to identify all of the txt file and export statistics and the number of

    private static int fileNumber = 0;
    private static int txtFileNumber = 0;
    private static int directoryNumber = 0;

    @Test
    public void IoFilePractise4() {
        String filePath = "D:\\";
        findFile(filePath);
        System.out.println("文件数:" + fileNumber);
        System.out.println("其中txt文件数:" + txtFileNumber);
        System.out.println("文件目录数:" + directoryNumber);
    }

    public void findFile(String filePath) {
        File file = new File(filePath);
        //遍历该路径下面的所有文件和目录
        File[] listFile = file.listFiles();
        //如果文件目录下面没有文件递归停止
        if(listFile==null)return;
        //递归遍历
        for (File fileTemp : listFile) {
            //如果是文件
            if (fileTemp.isFile()) {
                fileNumber++;
                System.out.println(fileTemp.getName() + "为文件");
                if (fileTemp.getName().endsWith(".txt")) {
                    txtFileNumber++;
                    System.out.println(fileTemp.getName() + "同时为txt文件");
                }
            } else if (fileTemp.isDirectory()) {
                directoryNumber++;
                System.out.println(fileTemp.getName() + "为文件目录");
                findFile(fileTemp.getPath());
            }
        }
    }
复制代码

IO basic categories

Most sub-category method is inherited from the parent class, the parent class method to understand clearly, using the subclass will be solved

InputStream class

method Methods Introduction
public abstract int read() Read data
public int read(byte b[]) The read data in the byte array
public int read(byte b[], int off, int len) Length len bytes read off position from the first data into the byte array
public void close() Read finished, close the stream, free up resources

OutputStream class

method Methods Introduction
public abstract void write(int b) Write a byte
public void write(byte b[]) All write byte array
public void write(byte b[], int off, int len) The start byte array from the off position, len bytes written
public void close() Close the output stream, after the stream is closed the output data can not be

Reader class

method Methods Introduction
public int read() Read a single character
public int read(char cbuf[]) Reads characters into the specified char array
abstract public int read(char cbuf[], int off, int len) Read off position from the length len of characters into the char array
abstract public void close() Close flow release related resources

Writer 类

method Methods Introduction
public void write(int c) Write a character
public void write(char cbuf[]) Writes an array of characters
abstract public void write(char cbuf[], int off, int len) Writes len number of characters from the off position the array of characters
abstract public void close() Close the output stream, after the stream is closed the output data can not be

FileInputStream和FileOutputStream

Reading a byte by byte

@Test
    public void FileRead() throws IOException {
        int count=0;//读取次数
        FileInputStream fis = new FileInputStream("D:\\file\\1.txt");
        int len;
        //一个字节一个字节的读取,读完返回-1
        while ((len = fis.read()) != -1) {
            System.out.print((char)len);
            count++;
        }
        System.out.println("读取次数:"+count);
        fis.close();
    }

复制代码

A plurality of read bytes

@Test
    public void FileRead() throws IOException {
        int count=0;//读取次数
        FileInputStream fis = new FileInputStream("D:\\file\\1.txt");
        byte[] n=new byte[1024];
        int len;
        //一个字节一个字节的读取,读完返回-1
        while ((len = fis.read(n)) != -1) {
            //new String(byte[] bytes, int offset, int length) 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String
            System.out.println(new String(n,0,len));
            count++;
        }
        System.out.println("读取次数:"+count);
        fis.close();
    }
复制代码

File Write

 @Test
    public void FileWrite() throws IOException {
        //追加写入
        FileOutputStream fos=new FileOutputStream("D:\\file\\1.txt",true);
        //写入单个字节
        fos.write(98);
        //写入多个字节
        fos.write(",Hello World!".getBytes());
        fos.close();
    }
复制代码

File copy

 @Test
    //1.txt的数据写入到2.txt
    public void FileCopy() throws IOException {
        //没有1.txt和2.txt文件需要提前创建
        FileOutputStream fos=new FileOutputStream("D:\\file\\2.txt");
        FileInputStream fis=new FileInputStream("D:\\file\\1.txt");
        int len;
        byte[] n=new byte[1024];
        while((len=fis.read(n))!=-1){
            fos.write(n,0,len);
        }
        fos.close();
        fis.close();
    }
复制代码

BuffereInputStream和BuffereOutputStream

Stream copy buffer

@Test
    public void FileBuffer() throws IOException {
        //里面需要有FileInputStream和FileOutStream的对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file\\1.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\file\\2.txt"));
        int len;
        while((len = bis.read()) != -1){
            bos.write(len);
        }
        bos.close();
        bis.close();
    }
复制代码

InputStreamReader和OutputStreamWriter

With a copy of the Chinese

  @Test
    public void FileStream() throws IOException {
        //补充:一个字符在GBK编码下占2个字节,即16位,在UTF-8编码下占三个字节,即24位
        InputStreamReader isr=new InputStreamReader(new FileInputStream("D:\\file\\1.txt"),"GBK");
        OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("D:\\file\\2.txt"),"GBK");
        int len;
        char[] n=new char[1014];
        while((len= isr.read(n))!=-1){
            System.out.println(new String(n,0,len));
            osw.write(n,0,len);
        }
        isr.close();
        osw.close();
    }
复制代码

ObjectInputStream和ObjectOutputStream

ObjectOutputStream actually serialize operation in convection, ObjectInputStream actually deserialize operation in convection to achieve serialization, must implement the Serializable interface, otherwise it is not possible serialization and de-serialization, if the object of the property plus the transient and static keyword, then the property will not be serialized.

Writing and reading objects

import java.io.Serializable;

public class Book implements Serializable {
    private String id;
    private String name;
    private int money;
    private transient int weight;

    @Override
    public String toString() {
        return "Book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", weight=" + weight +
                '}';
    }

    public Book(String id, String name, int money, int weight) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.weight = weight;
    }
   ----- getter and setter-----
}

 @Test
    public void ObjectTest() throws IOException, ClassNotFoundException {
        //先写入对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\file\\1.txt", true));
        oos.writeInt(99);
        oos.writeObject(new Book("001", "我的中国梦", 100,45));
        oos.close();
        //再读取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\file\\1.txt"));
        int readInt = ois.readInt();
        Book book = (Book) ois.readObject();
        System.out.println(readInt);
        System.out.println(book);
        ois.close();
    }
复制代码

end

As a java beginner, the IO will almost understand this point, the latter may need to constantly be learning based on actual interest or project. I am also a java novice, still in school, poor foundation java, write blog is mainly the aim of studying the mentality, if you have written above does not want to point out places.

Guess you like

Origin juejin.im/post/5d8af4d4e51d4578003fdcca