java - IO (Input Output)

Guide package

The java "flow" are located java.io package, referred to IO (input and output) stream;

字节流
java.io.InputStream
java.io.OutputStream
字符流
java.io.Reader
java.io.Writer

Byte stream

Common method

InputStream
Method Description Functional Description
int read() 8-bit byte read from the input stream, to convert his integer between 0 to 255, and returns an integer
int read(byte[] b) A number of bytes read from the input stream, save them to a specified byte array parameter b, returns an integer representing the number of bytes read
int read(byte[] b,int off,int len) A number of bytes read from the input stream, the parameter save them to a specified byte array b, OFF is not specified number of bytes of data starting start saving index, len denotes the number of bytes to read
void close() Closes this input stream and releases related to the flow of all system resources
OutputStream
Method Description Functional Description
void write(int b) Writing a byte to the output stream
void write(byte[] b) All the parameters b bytes written to the specified byte array input stream
void write(byte[] b,int off,int len) The specified byte array starting at offset off len bytes into the input stream
void flush() Refresh this input stream and force all buffered output bytes to write
void close() Closes this input stream and releases any system resources associated with this stream

Write byte stream file

FileInputStream is a subclass of InputStream, which is byte operation file input stream, specifically for reading the data file

import java.io.*;

public class Temp{
    public static void main(final String[] args) throws Exception {
        final FileInputStream in = new FileInputStream("D:\\myfile\\java\\io\\temp.txt");
        int b = 0;
        while(true){
            b = in.read();
            if(b == -1){
                break;
            }
            System.out.println(b);
        }
        in.close();

    }
}

FileOutputStream is a subclass of OutputStream, which is byte stream file operations, specifically for writing data file; additions to the existing file, the file transfer can be used to create a function FileOutputStream (String fileName, boolean append)

//导包
import java.io.FileOutputStream;

public class FileOutputStream_Test{
    public static void main(String[] args) throws Exception{
//        FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\Java\\learn\\temp.txt");
        //向文件中增加内容
        FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\Java\\learn\\temp.txt",true);
        String str = "Angelong";
        byte[] b = str.getBytes();
        for(int i = 0; i < b.length ;i++ ){
            out.write(b[i]);
        }
        out.close();
    }
}

Copies of documents

import java.io.FileInputStream;     //输入流包
import java.io.FileOutputStream;    //输出流包

public class Copy_test{
    public static void main(String[] args) throws Exception{
        FileInputStream in = new FileInputStream("D:\\myfile\\java\\Java\\learn\\temp.txt");
        FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\Java\\learn\\io\\temp.txt");
        int len;
        while ((len = in.read()) != -1){
            out.write(len);
        }
        in.close();
        out.close();
    }
}

Buffer byte stream

import java.io.FileInputStream;     //输入流包
import java.io.FileOutputStream;    //输出流包

public class Copy_test{
    public static void main(String[] args) throws Exception{
        FileInputStream in = new FileInputStream("D:\\myfile\\java\\Java\\learn\\temp.txt");
        FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\Java\\learn\\io\\temp.txt");
        int len;
        while ((len = in.read()) != -1){
            out.write(len);
        }
        in.close();
        out.close();
    }
}

Byte stream buffer

Provided with two packets buffered in the IO byte stream, respectively BufferedInputStream and BufferedOutputStream The , method of their construction receive InputStream and OutputStream type parameter as an object to provide a buffering function to read and write transactions;

import java.io.FileInputStream;     //输入流包
import java.io.FileOutputStream;    //输出流包

public class Copy_test{
    public static void main(String[] args) throws Exception{
        FileInputStream in = new FileInputStream("D:\\myfile\\java\\Java\\learn\\temp.txt");
        FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\Java\\learn\\io\\temp.txt");
        int len;
        while ((len = in.read()) != -1){
            out.write(len);
        }
        in.close();
        out.close();
    }
}

Character stream

Basic Usage

Two top-level parent classes: Reader and Writer
Reader: character-input stream is used to read characters from a source device;
Writer: character input stream for writing characters to a target device;
important subclasses:
FileReader and FileWriter for reading and writing files
BufferedReader and BufferedWriter stream having a buffer function is, they may be used to improve the efficiency of read and write;

Character stream file operations

Read the file using the FileReader

import java.io.FileReader;

public class FileReader_test{
    public static void main(String[] args) throws Exception{
        FileReader reader = new FileReader("D:\\myfile\\java\\Java\\learn\\temp.txt");
        int ch;
        while((ch = reader.read()) != -1){  //读取二进制数据
            System.out.print((char) ch);    //强行转换为char类型
        }
        reader.close();
    }
}

Use FileWriter to write files

import java.io.FileWriter;

public class FileWriter_test{
    public static void main(String[] args) throws Exception{
        FileWriter witer = new FileWriter("D:\\myfile\\java\\Java\\learn\\temp.txt",true);
        String test = "So hot !";
        witer.write(test);
        witer.write("\r\n");
        witer.close();
    }
}

Packet stream
BufferedReader character input stream for packaging
BufferedWriter character output stream for packaging
Note: There is a significant BufferedReader readLine (), which is used to read a line of text;

import java.io.*;
public class Buff{
	public static void main(String[] args) throws Exception{
		FileReader reader = new FileReader("Temp.txt");
		BufferedReader br = new BufferedReader(reader);
		FileWriter writer = new FileWriter("java.txt");
		BufferedWriter bw = new BufferedWriter(writer);
		String str;
		while ((str = br.readLine()) != null){
			bw.write(str);
			bw.newLine();
		}
		br.close();
		bw.close();
	}
}

File type

Common File class constructor

Method Statement Functional Description
File(String pathname) To create a new File object through a string type file path specified
File(String parent,String child) Create a File object based on a specified path string type of parent and child a path string type (including file name)
File(File parent Strng child) Create a File object parent paths and sub-paths according to the specified class Fie string type (including the file name)

File common method

Method Statement Functional Description
boolean exists() Judge File object corresponding to the file or directory exists, if there ture is returned, otherwise false
boolean delete() Delete File object corresponding to the file or directory, delete if successful returns true, false otherwise
boolean createNewFile() When the File object corresponding to the file does not exist, the method will build a new file specified by this File object, if successful, create returns true, false otherwise
String getName() Returns the name of the File object represents a file or folder
getPath () File object corresponding to the return path
String getAbsolutePath Returns the File object corresponds to an absolute path (on UNIX / Linux systems, if the path is a slash / beginning; then the path is the absolute path; on Windows systems, if the path is from the beginning of the letter, the the Road)
String getParent() Back File object corresponding to the parent directory of the directory (i.e., the directory does not contain the last return subdirectory)
boolean canRead() Analyzing File object corresponding file or directory is read, it returns true if the readable, false otherwise
boolean canWrite () File corresponding to the object is determined whether the file or directory can be written, if writable returns true, false otherwise
boolean isFile() File corresponding to the object is determined whether the document (not a directory), returns true if the file, false otherwise
boolean isDirectory() Analyzing File corresponding to the object is a directory (not file), if the directory returns true, false otherwise
boolean isAbsolute() Determine whether the File object corresponding to the file or directory is an absolute path
long lastModified() Return at 0:00:00 on January 1, 1970 to file was last modified time of milliseconds
long length() Returns the contents of the file length
String[]list() 列出指定且录的全部内容,只是列出名称
File[]listFiles() 返回一个包含了File 对象所有子文件和子目录的File数组
Select_File.java
import java.io.File;
import java.io.IOException;

public class Select_File{
    public static void main(String[] args){
        File file = new File("D:\\myfile\\java\\Java\\learn\\Temp.txt");
        //获取文件名称
        System.out.println("File name:" + file.getName());
        //获取相对路径
        System.out.println("File path:" + file.getPath());
        //获取绝对路径
        System.out.println("File absolute:" + file.getAbsolutePath());
        //获取文件父路径
        System.out.println("File parent:" + file.getParent());
        //判断文件是否可读
        System.out.println(file.canRead()?"Read yes":"Read no");
        //判断文件是否可读
        System.out.println(file.canWrite()?"Writer yes":"Writer no");
        //判断是否是一个文件
        System.out.print(file.isFile()?"is a file":"not a file");
        //判断是否是一个目录
        System.out.print(file.isDirectory()?"is dirctory":"not dirctory");
        //判断是否是一个绝对路径
        System.out.print(file.isAbsolute()?"is absolute":"not absolute");
        //获得文件最后的修改时间
        System.out.println("Modified lost time:" + file.lastModified());
        //获取文件大小
        System.out.print("File size:" + file.length()+"bytes");
        //是否成功删除
        System.out.print("Delete File is:" + file.delete());
    }
}
遍历目录下的文件

Find_File.java

import java.io.File;

public class Find_File{
    public static void main(String[] args){
        File file = new File("D:\\myfile");
        //判断是否是一个目录
        System.out.println("is Directory:" + file.isDirectory());
        if(file.isDirectory()){         //如果是一个目录
            String[] names = file.list();   //获取目录下的所有文件名
            for(String name : names){   
                System.out.println(name);      //输出所有文件名
            }
        }
    }
}
删除文件及目录

仅删除文件

import java.io.*;

public class Delete_File{
    public static void main(String[] margs){
        File file = new File("D:\\新建文本文档.txt");
        if(file.exists()){
            System.out.println(file.delete());
        }
    }
}

删除文件及目录

import java.io.*;

public class Delete_Drectory{
    public static void main(String[] args){
        File file = new File("D:\\myfile\\java\\learn");
        deleteDir(file);
    }
    public static void deleteDir(File dir){
        if(dir.exists()){
            File[] files = dir.listFiles();
            for(File file : files){
                if(file.isDirectory()){
                    deleteDir(file);
                }else{
                    file.delete();
                }
            }
            dir.delete();
        }
    }
}
发布了9 篇原创文章 · 获赞 0 · 访问量 113

Guess you like

Origin blog.csdn.net/weixin_44439071/article/details/103920758