Java explains the basic operation cases of files

  • 2021-10-24 23:02:09
  • OfStack

File file class

java. io. File are important classes for files and directories (JDK6 and previously only 1) Directories are also represented using the File class The File class is independent of the operating system, but is restricted by the permissions of the operating system Commonly used methods createNewFile , delete , exists , getAbsolutePath , getName , getParent , getPath isDirectory , isFile , length , listFiles , mkdir , mkdirs File does not deal with specific file contents, only attributes

public static void main(String[] args) {
    //  Create Directory 
    File directory = new File("D:/temp");
    boolean directoryDoesNotExists = ! directory.exists();
    if (directoryDoesNotExists) {
        // mkdir Is to create a single-level directory 
        // mkdirs Is to create multiple levels of directories continuously 
        directory.mkdirs();

    }
    //  Create a file 
    File file = new File("D:/temp/test.txt");
    boolean fileDoesNotExsits = ! file.exists();
    if (fileDoesNotExsits) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //  Traversal directory All file messages under 
    File[] files = directory.listFiles();
    for (File file1 : files) {
        System.out.println(file1.getPath());
    }

}

Run results:

D:\temp\test.txt

Java NIO

The new file system classes Path, Files, DirectoryStream, FileVisitor and FileSystem are beneficial supplements to java. io. File. File copying and moving file relative path recursively traversing directory recursively deleting directory

Class Path


public static void main(String[] args) {
    // Path And java.io.File Basically similar 
    Path path = FileSystems.getDefault().getPath("D:/temp", "abc.txt");
    // D:/  Return 1 D:/temp  Return 2
    System.out.println(path.getNameCount());

    //  Use File Adj. toPath() Method gets Path Object 
    File file = new File("D:/temp/abc.txt");
    Path path1 = file.toPath();
    System.out.println(path.compareTo(path1)); //  The result is 0  Explain two path Equality 
    //  Get Path Method 3
    Path path3 = Paths.get("D:/temp", "abc.txt");
    //  Determine whether the file is readable 
    System.out.println(" Is the file readable : " + Files.isReadable(path));
}

Class Files


public static void main(String[] args) {
    //  Move a file 
    moveFile();
    //  Access file properties 
    fileAttributes();
    //  Create Directory 
    createDirectory();
}

private static void createDirectory() {
    Path path = Paths.get("D:/temp/test");
    try {
        //  Create a folder 
        if (Files.notExists(path)) {
            Files.createDirectory(path);
        } else {
            System.out.println(" Folder creation failed ");
        }
        Path path2 = path.resolve("a.java");
        Path path3 = path.resolve("b.java");
        Path path4 = path.resolve("c.txt");
        Path path5 = path.resolve("d.jpg");
        Files.createFile(path2);
        Files.createFile(path3);
        Files.createFile(path4);
        Files.createFile(path5);

        //  Traversal output without conditions 
        DirectoryStream<Path> listDirectory = Files.newDirectoryStream(path);
        for (Path path1 : listDirectory) {
            System.out.println(path1.getFileName());
        }
        //  Create 1 With filters that filter file names with java txt Ending file 
        DirectoryStream<Path> pathsFilter = Files.newDirectoryStream(path, "*.{java,txt}");
        for (Path item : pathsFilter) {
            System.out.println(item.getFileName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("all")
private static void fileAttributes() {
    Path path = Paths.get("D:/temp");
    //  Determine whether it is a directory 
    System.out.println(Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS));
    try {
        //  Get the underlying properties of the file 
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        //  Determine whether it is a directory 
        System.out.println(attributes.isDirectory());
        //  Get the last time the file was modified 
        System.out.println(new Date(attributes.lastModifiedTime().toMillis()).toLocaleString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static void moveFile() {
    Path from = Paths.get("D:/temp", "text.txt");
    //  Move files to D:/temp/test/text.txt,  Replace the target file if it exists 
    Path to = from.getParent().resolve("test/text.txt");
    try {
        //  File size bytes
        System.out.println(Files.size(from));
        //  Call the file move method and replace the target file if it already exists 
        Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Recursive traversal to find the specified file


public class Demo2 {
    public static void main(String[] args) {
        //  Find with .jpg Ending 
        String ext = "*.jpg";
        Path fileTree = Paths.get("D:/temp/");
        Search search = new Search(ext);
        EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        try {
            Files.walkFileTree(fileTree, options, Integer.MAX_VALUE, search);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Search implements FileVisitor {
    private PathMatcher matcher;
    public Search(String ext) {
        this.matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
    }

    public void judgeFile(Path file) throws IOException {
        Path name = file.getFileName();
        if (name != null && matcher.matches(name)) {
            //  File name matching 
            System.out.println(" Matching file name : " + name);
        }
    }
    //  Called before accessing the directory 
    @Override
    public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    //  Called when accessing a file 
    @Override
    public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
        judgeFile((Path) file);
        return FileVisitResult.CONTINUE;
    }
    //  Called after file access fails 
    @Override
    public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }
    //  Visit 1 Called after directories 
    @Override
    public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
        System.out.println("postVisit: " + (Path) dir);
        return FileVisitResult.CONTINUE;
    }
}

Run results:

Matching filename: d. jpg
postVisit: D:\temp\test
postVisit: D:\temp

IO packet for Java

Java can only read and write files in the form of data flow. java. Node class in io package: Read and write files directly. Wrapper class: 1. Conversion class: Byte/character/data type conversion class. 2. Decoration class: Decoration node class.

Node class

Directly manipulate file classes InputStream, OutStream (bytes) FileInputStream, FileOutputStream Reader, Writer (characters) FileReader, FileWriter

Transformation class

From character to byte conversion InputStreamReader: File read byte, converted to Java can understand the character OutputStreamWriter: Java character into byte input into the file

Decorative category

DataInputStream, DataOutputStream: Encapsulated data stream BufferedInputStream, BufferOutputStream: Cached byte stream BufferedReader, BufferedWriter: Cached character stream

Reading and writing text files

Write operation


public static void main(String[] args) {
    writeFile();
}

public static void writeFile(){
    try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/temp/demo3.txt")))) {
        bw.write("hello world");
        bw.newLine();
        bw.write("Java Home");
        bw.newLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Demo3. txt file contents

hello world
Java Home

Read operation


public static void main(String[] args) {
    readerFile();
}

private static void readerFile() {
    String line = "";
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:/temp/demo3.txt")))) {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Run results:

hello world
Java Home

Reading and writing binary files java


public static void main(String[] args) {
    writeFile();
}

private static void writeFile() {
    try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("D:/temp/test.dat")))) {
        dos.writeUTF("hello");
        dos.writeUTF("hello world is test bytes");
        dos.writeInt(20);
        dos.writeUTF("world");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

File content

hellohello world is test bytesworld

Read operation


public static void main(String[] args) {
   readFile();
}

private static void readFile() {
    try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("D:/temp/test.dat")))) {
        System.out.println(in.readUTF() + in.readUTF() + in.readInt() + in.readUTF());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Run results:

hellohello world is test bytes20world

Reading and Writing of ZIP File

zip file operation class: in java. util. zip package Subclasses of java. io. InputStream, java. io. OutputStream ZipInputStream, ZipOutputStream compressed file input/output stream ZipEntry compression term

Multiple file compression


//  Multiple file compression 
public static void main(String[] args) {
    zipFile();
}
public static void zipFile() {
    File file = new File("D:/temp");
    File zipFile = new File("D:/temp.zip");
    FileInputStream input = null;
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
        //  Add a comment 
        zos.setComment(new String(" Multiple individual file compression ".getBytes(),"UTF-8"));

        //  Compression process 
        int temp = 0;
        //  Determine whether it is a folder 
        if (file.isDirectory()) {
            File[] listFile = file.listFiles();
            for (int i = 0; i < listFile.length; i++) {
                    //  Defines the output stream of the file 
                    input = new FileInputStream(listFile[i]);
                    //  Settings Entry Object 
                    zos.putNextEntry(new ZipEntry(file.getName() +
                            File.separator + listFile[i].getName() ));
                    System.out.println(" Compressing : " + listFile[i].getName());
                    //  Read content 
                    while ((temp = input.read()) != -1) {
                        //  Compressed output 
                        zos.write(temp);
                    }
                    //  Close the input stream 
                    input.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Note: The compressed folder cannot have subdirectories, otherwise FileNotFoundException: D:\ temp\ test (access denied) will be reported. ), which is due to input = new FileInputStream (listFile [i]); The file type read is caused by the folder

Multiple file decompression


//  Multiple file decompression 
public static void main(String[] args) throws Exception{
    //  To be decompressed zip File, which needs to be found in zip File, read data to the Java Medium 
    File file = new File("C:\\Users\\Wong\\Desktop\\test.zip");

    //  When outputting files, there should be folder operation 
    File outFile = null;
    //  Instantiation ZipEntry Object 
    ZipFile zipFile = new ZipFile(file);

    //  Define the unzipped file name 
    OutputStream out = null;
    //  Define the input stream and read each Entry
    InputStream input = null;
    //  Every 1 Compression Entry
    ZipEntry entry = null;
    
    //  Defining a compressed input stream , Instantiation ZipInputStream
    try (ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file))) {
        //  Traverse the files in the compressed package 
        while ((entry = zipInput.getNextEntry()) != null) {
            System.out.println(" Decompression  " + entry.getName().replaceAll("/", "") + "  Documents ");
            //  Define the file path for output 
            outFile = new File("D:/" + entry.getName());
            
            boolean outputDirectoryNotExsits = !outFile.getParentFile().exists();
            //  When the output folder does not exist 
            if (outputDirectoryNotExsits) {
                //  Create Output Folder 
                outFile.getParentFile().mkdirs();
            }
            
            boolean outFileNotExists = !outFile.exists();
            //  When the output file does not exist 
            if (outFileNotExists) {
                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.createNewFile();
                }
            }

            boolean entryNotDirctory = !entry.isDirectory();
            if (entryNotDirctory) {
                input = zipFile.getInputStream(entry);
                out = new FileOutputStream(outFile);
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    out.write(temp);
                }
                input.close();
                out.close();
                System.out.println(" Successful decompression ");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Related articles: