Junior sister learning javaio: file copy and file filter

brief introduction

For a Linux command, the younger martial sister insisted on me to teach her how to implement it in Java. Alas, I feel powerless to stand such a fine younger martial sister. It's really difficult to be a senior brother.

Copy files using java

Today, my younger martial sister found me: Senior brother F, can you tell me how to copy the file?

Copy files? Isn't it a very simple thing? If you have read access to the file, just do so.

cp www.flydean.com www.flydean.com.back

Of course, if it is a directory, you can also add two parameters: traversal and forced copy:

cp -rf srcDir distDir

Such a simple Linux command, don't tell me you won't.

Younger martial sister smiled: elder martial brother F, I don't want to use Linux commands. I just want to use Java. Aren't I learning Java? Of course, you should find the right opportunity to practice one. Teach me quickly.

In that case, I'll start. There are actually three methods for copying files in Java. You can use the traditional file reading and writing method or the copy method provided in the latest NiO.

Of course, using traditional methods is not as fast as NiO, nor as concise as NiO. Let's take a look at how to use traditional file reading and writing methods to copy files:

    public  void copyWithFileStreams() throws IOException
    {
        File fileToCopy = new File("src/main/resources/www.flydean.com");
        File newFile = new File("src/main/resources/www.flydean.com.back");
        newFile.createNewFile();
        try(FileOutputStream output = new FileOutputStream(newFile);FileInputStream input = new FileInputStream(fileToCopy)){
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0)
            {
                output.write(buf,bytesRead);
            }
        }
    }

In the above example, we first define two files, then generate OutputStream and InputStream from the two files, and finally read data from input to OutputStream in the form of byte stream. Finally, we complete the copy of the file.

The traditional file IO copy is cumbersome and slow. Let's see how NiO can be used to complete this process:

public  void copyWithNIOChannel() throws IOException
    {
        File fileToCopy = new File("src/main/resources/www.flydean.com");
        File newFile = new File("src/main/resources/www.flydean.com.back");

        try(FileInputStream inputStream = new FileInputStream(fileToCopy);FileOutputStream outputStream = new FileOutputStream(newFile)){
            FileChannel inChannel = inputStream.getChannel();
            FileChannel outChannel = outputStream.getChannel();
            inChannel.transferTo(0,fileToCopy.length(),outChannel);
        }
    }

As we mentioned earlier, a very important concept in NiO is channel, which can be copied directly at the channel level by building the channel channels of source files and target files. As shown in the above example, we called inchannel Transferto finished copying.

Finally, there is a simpler method to copy NiO files:

public  void copyWithNIOFiles() throws IOException
    {
        Path source = Paths.get("src/main/resources/www.flydean.com");
        Path destination = Paths.get("src/main/resources/www.flydean.com.back");
        Files.copy(source,destination,StandardCopyOption.REPLACE_EXISTING);
    }

You can directly use the copy method provided by the tool class files.

Using file filter

Great, younger martial sister adores: elder martial brother F, I have another need, that is, I want to delete the in a directory Log file at the end of log. Is this requirement very common? How does senior brother f usually operate?

I usually do this with one Linux command. If I'm not sure, I'll use two:

rm -rf *.log

Of course, if necessary, we can also implement it in Java.

Java provides two filters that can be used to implement this function.

These two filters are Java io. Filenamefilter and Java io. FileFilter:

@FunctionalInterface
public interface FilenameFilter {
    boolean accept(File dir,String name);
}
@FunctionalInterface
public interface FileFilter {
    boolean accept(File pathname);
}

Both interfaces are functional, so their implementation can be directly replaced by lambda expressions.

The difference between the two is that filenamefilter filters the file name and the directory where the file is located. The filefilter directly filters the target file.

There is no concept of directory in Java. A directory is also represented by file.

The above two are very similar. Let's take filenamefilter as an example to see how to delete it Log file:

public void useFileNameFilter()
    {
        String targetDirectory = "src/main/resources/";
        File directory = new File(targetDirectory);

        //Filter out all log files
        String[] logFiles = directory.list( (dir,fileName)-> fileName.endsWith(".log"));

        //If no log file found; no need to go further
        if (logFiles.length == 0)
            return;

        //This code will delete all log files one by one
        for (String logfile : logFiles)
        {
            String tempLogFile = targetDirectory + File.separator + logfile;
            File fileDelete = new File(tempLogFile);
            boolean isdeleted = fileDelete.delete();
            log.info("file : {} is deleted : {} ",tempLogFile,isdeleted);
        }
    }

In the above example, we use directory List method, pass in the filter created by lambda expression to realize the filtering effect.

Finally, we delete the filtered file. Achieved the goal.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>