Java files and IO

Foreword to know the document

A file in a narrow sense. For I/O devices with persistent storage such as hard disks, when we want to save data, we often do not save it as a whole, but independently save it as individual units. This independent unit is abstracted into a file Concept, files are managed by folders and directories;

Absolute and Relative Paths

Absolute path: It is fixed, unchanging, and the only path
Relative path: It is a path derived from the node you are currently at

Ordinary files and binary files

Ordinary file: can be viewed by opening with notepad
Binary file: cannot be viewed by opening with notepad
You can also see the encoding format of the character set below

Manipulating files in Java

File class

Construction method
insert image description here

 public static void main(String[] args) throws IOException {
    
    
        File file = new File("..\\hello-world.txt"); // 并不要求该文件真实存在
        // 得到父目录文件的路径
        System.out.println(file.getParent());
        // 得到文件名字
        System.out.println(file.getName());
        // 得到文件路径
        System.out.println(file.getPath());
        // 得到文件绝对路径
        System.out.println(file.getAbsolutePath());
        // 得到文件相对路径
        System.out.println(file.getCanonicalPath());
        // 判断文件是否存在
         System.out.println(file.exists());
         // 判断文件是否是目录
        System.out.println(file.isDirectory());
        // 判断是不是一个普通文件
        System.out.println(file.isFile());
        // 创建一个新的文件
        System.out.println(file.createNewFile());
        //删除一个文件
         System.out.println(file.delete());
         //创建目录
          System.out.println(dir.mkdir());
          //文件重命名
           System.out.println(file.renameTo(dest));
     
   }

file reading and writing

InputStream

int read() reads a byte of data, returns -1 to indicate that it has been completely read
int read(byte[] b) reads at most b.length bytes of data into b, and returns the actual number read;- 1 means and after reading
int read(byte[] b, int off, int len) read at most len ​​- off bytes of data into b, start from off, and return the actual number read; -1 means and After reading
void close() closes the byte stream

InputStream is just an abstract class, and a concrete implementation class is required to use it.

 try (InputStream is = new FileInputStream("hello.txt")) {
    
    
            while (true) {
    
    
                int b = is.read();
                if (b == -1) {
    
    
                    // 代表文件已经全部读完
                    break;
               }
                
                System.out.printf("%c", b);
           }
       }
public static void main(String[] args) throws IOException {
    
    
//文件内容中填充中文
        try (InputStream is = new FileInputStream("hello.txt")) {
    
    
            byte[] buf = new byte[1024];
            int len;
            while (true) {
    
    
                len = is.read(buf);
                if (len == -1) {
    
    
                    // 代表文件已经全部读完
                    break;
               }
                // 每次使用 3 字节进行 utf-8 解码,得到中文字符
                // 利用 String 中的构造方法完成
                // 这个方法了解下即可,不是通用的解决办法
                for (int i = 0; i < len; i += 3) {
    
    
                    String s = new String(buf, i, 3, "UTF-8");
                    System.out.printf("%s", s);
               }
           }
       }
   }

It is very cumbersome and difficult to directly use InputStream to read character types, so we use a class that we are familiar with to complete the work, which is the Scanner class.

try (InputStream is = new FileInputStream("hello.txt")) {
    
    
           try (Scanner scanner = new Scanner(is, "UTF-8")) {
    
    
               while (scanner.hasNext()) {
    
    
                   String s = scanner.next();
                   System.out.print(s);
               }
           }
       }

OutputStream

void write(int b) write the data to be given to the byte
void write(byte[] b) write all the data in the character array of b into the os
int write(byte[]b, int off, int len) will b The data starting from off in this character array is written into os, and a total of len pieces are written.
void close() closes the byte stream
void flush() Important: We know that the speed of I/O is very slow, so most of the OutputStream In order to
reduce the number of device operations, when writing data, the data will be temporarily written into
a designated area of ​​the memory, and the data will not be actually
written into . This area is generally called for the buffer. But one result is that some of the data we write
is likely to be left in the buffer. It is necessary to call the flush (refresh) operation at the end or at a suitable position
to flush the data to the device.

 try (OutputStream os = new FileOutputStream("output.txt")) {
    
    
 // 字符写入
            os.write('H');
            os.write('e');
            os.write('l');
            os.write('l');
            os.write('o');
            // 不要忘记 flush
            os.flush();
       }
 try (OutputStream os = new FileOutputStream("output.txt")) {
    
    
           String s = "Nothing";
            byte[] b = s.getBytes();
            os.write(b);
          
            // 不要忘记 flush
            os.flush();
       }
 try (OutputStream os = new FileOutputStream("output.txt")) {
    
    
            String s = "你好中国";
            byte[] b = s.getBytes("utf-8");
         os.write(b);
            
            // 不要忘记 flush
            os.flush();
       }

Guess you like

Origin blog.csdn.net/qq_56454895/article/details/131693921