JAVA study notes 09-file class, IO stream

File class

1. Construction method

public File (String pathname): Creates a new File instance by the given path string into an abstract pathname
path may be the end of the file or folder is the end of
the path may be a relative path or an absolute path
path can be Existing or non-existing
Create a File object, just encapsulate the string path as a File object, regardless of the existence

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        show();
    }

    private static void show() {
    
    
        File fl=new File("D:\\JAVA\\File\\text.txt");
        System.out.println(fl); //D:\JAVA\File\text.txt
    }
}

public File(String parent,String child): Create a new File instance from the parent path name string and the child path name string
parent: parent path
child: child path
Benefits: parent path and child path can be written separately, flexible to use

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        show();
    }

    private static void show() {
    
    
        File fl=new File("D:\\JAVA\\File","text.txt");
        System.out.println(fl); //D:\JAVA\File\text.txt
    }
}

public File (File parent, String child): Create a new File instance from the parent abstract path name and the child path name string.
Benefits: The parent path can use the File method to perform some operations on the path

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        show();
    }

    private static void show() {
    
    
        File parent=new File("D:\\JAVA\\File");
        File fl=new File(parent,"text.txt");
        System.out.println(fl); //D:\JAVA\File\text.txt
    }
}

2. Common methods

public String getAbsolutePath(): Returns the absolute path string of this File
public String getPath(): Converts this File to a path name string
public String getName(): Returns the name of the file or directory represented by this File
public long length(): Returns the length of the file represented by this File

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        File f=new File("F:\\JAVA\\File");
        System.out.println(f.getAbsolutePath());
        System.out.println(f.getPath());
        System.out.println(f.getName());
        System.out.println(f.length());
        /*
        F:\JAVA\File
        F:\JAVA\File
        File
        0
         */
    }
}

Judging method
public boolean exists(): Whether the file or directory represented by this File actually exists
public boolean isDirectory(): Whether this File represents a directory
public boolean isFile(): Whether this File represents a file

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        File f=new File("F:\\JAVA\\File");
        System.out.println(f.exists());
        System.out.println(f.isDirectory());
        System.out.println(f.isFile());
        /*
        true
        true
        false
         */
    }
}

Delete method
public boolean createNewFile(): If and only if the file with the name does not exist yet, create a new empty folder
1. This method can only create files, not folders
2. The path to create files must exist , Otherwise an exception will occur

public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File f=new File("F:\\JAVA\\File\\text.txt");
        boolean b=f.createNewFile();	//只能创建文件,不能创建文件夹
        System.out.println(b);
    }
}

public boolean delete(): delete the file or directory represented by this File.
If there is a file in the folder, it returns false; if there is no file, it returns true

public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File f1=new File("F:\\JAVA\\File\\text\\text1\\text2");
        boolean b1=f1.delete();
        System.out.println(b1);
    }
}

public boolean mkdir(): create a directory represented by this File, create a single-level empty folder
public boolean mkdirs(): create a directory represented by this File, including any necessary but non-existent parent directories, create a single-level empty folder , You can also create multi-level folders

public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File f1=new File("F:\\JAVA\\File\\text");
        boolean b=f1.mkdir();
        System.out.println(b);
        File f2=new File("F:\\JAVA\\File\\text\\text1\\text2");
        boolean b2=f2.mkdirs();
        System.out.println(b2);
    }
}	//只创建文件夹

Directory traversal
public String[] list(): returns a String array, representing all sub-files or directories in the
File directory public File[] listFiles(): returns a File array, representing all files or directories in the File directory

public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File f1=new File("F:\\JAVA");
        //获取当前目录下的文件以及文件夹的名称
        String[] names=f1.list();
        for (String name : names) {
    
    
            System.out.println(name);
        }
        //获取当前目录下的文件以及文件夹对象,只要拿到了文件对象,那么就可以获取更多信息
        File[] files=f1.listFiles();
        for (File file : files) {
    
    
            System.out.println(file);
        }
    }
}

IO style

1.IO overview

Input stream: a stream that reads data from other devices to memory.
Output stream: a stream that writes data out of memory to other devices.

2. Byte stream

Byte output stream
public void close(): Close this output stream and release any system resources associated with it
public void flush(): Flush this output stream and force any buffered output bytes to be written
public void write(byte [] b): Write b.length bytes from the specified byte array to this output stream
public void write(byte[] b,int off,int len): Write len bytes from the specified byte array, Start output from offset off to this output stream
public abstract void write(int b): output the specified byte to the stream
Construction method:
FileOutputStream(String name): create an output that writes data to a file with the specified name File Stream
FileOutputStream(File file): Creates a file output stream that writes data to the file represented by the specified File object. The
role of the construction method:
1. Create a FileOutputStream object
2. Create it according to the file/file path passed in the construction method An empty file
3. The FileOutputStream object will be assigned to the created file

public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
        FileOutputStream fos=new FileOutputStream("F:\\JAVA\\File\\text1.txt");
        //调用FileOutputStream对象中的write方法,把数据写入到文件中
        fos.write(97);
        //释放资源
        fos.close();
    }
}
public class Demo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
        FileOutputStream fos=new FileOutputStream(new File("F:\\JAVA\\File\\text2.txt"));
        //调用FileOutputStream对象中的write方法,把数据写入到文件中
        /*public void write(byte[] b)一次写多个字节
        如果写的第一个字节是正数,那么现实的时候会查询ASCII表
        如果写的第一个字节是负数,那第一个字节会和第二个字节组成一个中文显示
         */
        byte[] bytes={
    
    65,66,67,68,69};
        //fos.write(bytes)  ABCDE
        fos.write(bytes,1,2);   //BC
        //释放资源
        fos.close();
    }
}

Continuation and line break:
The construction method using two parameters:
FileOutputStream(String name, boolean append): Create an output file stream that writes data to the file with the specified name
FileOutputStream(File file, boolean): Create a specified file File output stream of data written in the file represented by the File object
Parameters:
name, file: path to write data
boolean append: true creating an object will not overwrite the original file, continue to write data at the end of the file; false create a new file overwrite Original file

public class Demo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        FileOutputStream fos=new FileOutputStream("F:\\JAVA\\File\\text1.txt",true);
        fos.write("Kobe".getBytes());
        fos.close();
    }
}

Newline symbol:

public class Demo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        FileOutputStream fos=new FileOutputStream("F:\\JAVA\\File\\text1.txt",true);
        for (int i=0;i<10;i++){
    
    
            fos.write("Kobe".getBytes());
            fos.write("\r\n".getBytes());
        }
        fos.close();
    }
}

Byte input stream
reads data from the hard disk into memory
int read(): reads the next byte of data from the input stream
int read(byte[] b): reads a certain number of words from the input stream Section, and store it in the buffer array b.
Construction method:
FileInputStream(String nmae)
FileInputStream(File file)
Function:
1. Create a FileInputStream object
2. Will read the file in the construction method specified by the FileInputStream object

public class Demo03 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建FileInputStream对象,构造方法中绑定要读取的数据
        FileInputStream fis=new FileInputStream("F:\\JAVA\\File\\text1.txt");
        //使用FileInputStream对象中的方法read,读取文件
/*       int len=fis.read();
        System.out.println(len);*/
        int len=0;
        while((len=fis.read())!=-1){
    
    
            System.out.println((char)len);
        }
        //释放资源
       fis.close();
    }
}
public class Demo03 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建FileInputStream对象,构造方法中绑定要读取的数据
        FileInputStream fis=new FileInputStream("F:\\JAVA\\File\\text2.txt");
        //使用FileInputStream对象中的方法read,读取文件
        byte[] bytes=new byte[1024];
        int len=0;
        while((len=fis.read(bytes))!=-1){
    
    
            System.out.println(new String(bytes,0,len));
            //用len记录长度使读取有效字节数
        }
        //释放资源
       fis.close();
    }
}

3. Character stream

Character input stream
public void close(): close this stream and release any system resources associated with this
public int read(): read a character from the input stream
public int read(char[) cbuf): read from the input stream Take some characters and store them in the character array cbuf
Construction method:
FileReader(File file): Create a new FileReader, given the File object to be read
FileReader(String fileName): Create a new FileReader, given File name
character output stream to be read
void write(int c): write a single character
void write(char[] cbuf): write character array
abstract void write(char[] cbuf,int off,int len): write Enter a certain part of the character array, the start index of the off array, the number of characters written by len
void write(String str): write a string
void write(String ,str,int off.int len): write a certain part of the string One part, the start index of the off string, the number of characters written by len
void flush(): flush the buffer of the stream
void close(): close the stream, but first flush

public class Demo05 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //使用FileWriter对象,构造方法中绑定要写入数据的目的地
        FileWriter fw=new FileWriter("F:\\\\JAVA\\\\File\\\\text2.txt");
        //使用FileWriter中的方法write,把数据写入到内存缓冲区(字符转换为字节的过程)
        fw.write(97);
        //使用FileWriter中的方法flush(),把内存缓冲区中的数据,刷新到文件中
        fw.flush();
        //释放资源
        fw.close();
    }
}

flush(): flush the buffer, the stream object can continue to use
close(): flush the buffer first, and then notify the system to release the resource, the stream object can no longer be used

public class Demo05 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //使用FileWriter对象,构造方法中绑定要写入数据的目的地
        FileWriter fw=new FileWriter("F:\\\\JAVA\\\\File\\\\text2.txt");
        char[] cs={
    
    'h','i','w','o','r','l','d'};
        fw.write(cs);
        fw.write(cs,2,2);
        fw.write("hello,world");
        fw.close();
    }
}

Continuation and line feed: Same as above

4. IO exception handling

JDK7: Add a () after try, the stream object can be defined in parentheses, then the scope of the stream object is valid in the try, the code in the try is executed, the stream object will be automatically released
JDK9: before the try Define the stream object, you can introduce the name of the stream object in () after try. The stream object can also be released one week after the try code is executed, without writing finally

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/106944695