Application example tutorial of FileUtils class
FileUtils class application
1. Write a file;
2. Read from the file;
3. Create a folder, including folders ;
4. Copy files and folders;
5. Delete files and folders;
6. Get files from URL address;
7. List files and folders by file filter and extension;
8. Compare file contents;
9. File last modification time;
10. Calculate checksum.
1. Method of copying files or folders:
Example:
1 public class CopyFileorDirectory { 2 public static void main(String[] args) throws Exception { 3 File file1 =new File("path1"); 4 File file2 =new File("path2"); 5 File file3 =new File("path3"); 6 File file4 =new File("path4"); 7 File file5 =new File("path5"); 8 //将文件复制到指定文件夹中,保存文件日期的时间。 9 // 该方法将指定源文件的内容复制到指定目标目录中相同名称的文件中。 10 // 如果不存在,则创建目标目录。如果目标文件存在,则该方法将覆盖它。 11 FileUtils.copyFileToDirectory(file1,file2);//文件不重命 12 //将文件复制到一个新的地方(重命名文件)并保存文件日期的时间。 13 FileUtils.copyFile(file1,file3); 14 15 //复制文件夹到指定目录下,如果指定目录不存在则创建 16 FileUtils.copyDirectoryToDirectory(file2,file4); 17 18 //复制文件夹到指定目录下并重命名 19 FileUtils.copyDirectory(file4,file5); 20 21 //该方法将指定的源目录结构复制到指定的目标目录中。 22 FileUtils.copyDirectory(file4,file5, DirectoryFileFilter.DIRECTORY); 23 24 // 复制文件夹下第一级内容中指定后缀文件 25 IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); 26 IOFileFilter txtFiles = FileFilterUtils.and(FileFileFilter.FILE, txtSuffixFilter); 27 FileUtils.copyDirectory(file4,file5, txtFiles); 28 29 // 复制文件目录结构及文件夹下第一级目录内指定后缀文件 30 FileFilter filter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, txtFiles); 31 FileUtils.copyDirectory(file4,file5, filter,false);//preserveFileDate参数默认为true。 32 33 //将字节从URL源复制到文件目的地。如果它们还不存在,则将创建到目的地的目录。如果已经存在,文件将被覆盖。 34 URL source = new URL("http://imgsrc.baidu.com/baike/pic/ewe.jpg"); 35 FileUtils.copyURLToFile(source,file5,1000,1000); 36 37 // 等待NFS传播文件创建,并强制执行超时。该方法重复测试File.exists(),直到它返回true,或直到秒内指定的最大时间。 38 File file = new File("/abc/"); 39 boolean d = FileUtils.waitFor(file,100); 40 System.out.println(d); 41 } 42 }
2. Method of deleting files or files
1 public class FileorDirectoryDelete { 2 public static void main(String[] args) throws Exception{ 3 File file = new File("path1"); 4 File directory = new File("path2"); 5 //递归删除一个目录(包括内容)。 6 FileUtils.deleteDirectory(directory); 7 8 //删除一个文件,不会抛出异常。如果文件是一个目录,删除它和所有子目录。 9 FileUtils.deleteQuietly(file); 10 11 //清理内容而不删除它。 12 FileUtils.cleanDirectory(directory); 13 14 //删除一个文件,会抛出异常 15 //如果file是文件夹,就删除文件夹及文件夹里面所有的内容。如果file是文件,就删除。 16 //如果某个文件/文件夹由于某些原因无法被删除,会抛出异常 17 FileUtils.forceDelete(file); 18 } 19 }
3. Create directory
1 public class CreatDirectory { 2 public static void main(String[] args) throws Exception { 3 File file = new File("path"); 4 //创建一个文件夹,如果由于某些原因导致不能创建,则抛出异常 5 //一次可以创建单级或者多级目录 6 FileUtils.forceMkdir(new File("/Users/wuguibin/Downloads/folder")); 7 //为指定文件创建文件的父级目录 8 FileUtils.forceMkdirParent(file); 9 } 10 }
4. Move files or folders
//移动文件夹,并重新命名 FileUtils.moveDirectory(new File("/Users/Downloads/file1"), new File("/Users/Downloads/file2/file3")); //移动文件夹,并给定是否重命名 FileUtils.moveDirectoryToDirectory(new File("/Users/Downloads/file1"), new File("/Users/Downloads/file2/"),false); //移动文件到指定文件夹中,并重新命名 FileUtils.moveFile(file1,new File("/Users/Downloads/海葡萄.jpen")); //移动文件到指定文件夹中,并给定是否创建文件夹 FileUtils.moveFileToDirectory(new File("/Users/Downloads/海葡萄.jpeg"), new File("/Users/Downloads/file2"),false);
5 , Determine whether the files are the same or contain relationships, get the size of the file or folder
//确定父目录是否包含指定子元素(一个文件或目录)。即directory是否包含file2,在比较之前,文件是标准化的。 boolean a = FileUtils.directoryContains(directory,file2); //比较两个文件的内容,以确定它们是否相同。 boolean b = FileUtils.contentEquals(file1, file2)
//Get the size of the specified file or folder, it may overflow and become a negative value
long l = FileUtils .sizeOf(file1);
System.out.println(l+"KB");
//Get the size of the specified file or folder without overflowing
BigInteger bi= FileUtils.sizeOfAsBigInteger(file1);
System.out.println(bi+"kb");
//Recursively calculate the size of a directory (the sum of the lengths of all files).
//Note that sizeOfDirectory() does not detect overflow, and if overflow occurs, the return value may be negative. The sizeOfDirectoryAsBigInteger() method does not overflow.
FileUtils.sizeOfDirectory(file1);
FileUtils.sizeOfDirectoryAsBigInteger(file1);
6. Compare the old and new files
//比较指定文件是否比参考文件创建或修改后时间晚 boolean b = FileUtils.isFileNewer(file1,file2)); //如果指定的文件比指定的日期更新。 SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd"); String date1 = "2017/06/20"; boolean c = FileUtils.isFileNewer(file1,date.parse(date1)); boolean d = FileUtils.isFileNewer(file1,23243); //指定文件创建或修改后的时间是否比参考文件或日期早 FileUtils.isFileOlder(file1,232434); FileUtils.isFileOlder(file1,System.currentTimeMillis());
7. Write Enter the file
//把集合里面的内容写入文件,以指定字符串结束写入 //void writeLines(File file,Collection<?> lines,String lineEnding,boolean append) ArrayList<String> list = new ArrayList<>(); String str1 = "Java"; String str2 = "JSP"; list.add(str1); list.add(str2); FileUtils.writeLines(file8,"GBK",list,"java",true); //把字符串写入文件 //参数1:需要写入的文件,如果文件不存在,将自动创建。 参数2:需要写入的内容 //参数3:编码格式 参数4:是否为追加模式( ture: 追加模式,把字符串追加到原内容后面) String data1 = "认真"; FileUtils.writeStringToFile(file,data1, "UTF-8", true); //把字节数组写入文件 byte [] buf = {13,123,34}; System.out.println(new String(buf)); FileUtils.writeByteArrayToFile(file13,buf,0,buf.length,true);
8. Read the file and obtain the input and output stream
//将文件的内容读入一个字符串中。 String str = FileUtils.readFileToString(file,"UTF-16" ); FileUtils.readFileToByteArray(file); //把文件读取到字节数组里面 byte[] readFileToByteArray(final File file) //把文件读取成字符串 ;Charset encoding:编码格式 String readFileToString(final File file, final Charset encoding) //把文件读取成字符串集合 ;Charset encoding:编码格式 List<String> list4 =FileUtils.readLines( new File("/Users/Shared/笔记/java.txt"),"UTF-8"); Iterator it = list4.iterator(); while (it.hasNext()){ Object obj=it.next(); System.out.println(obj); } //获取输入流 FileUtils.openInputStream(file); //获取输出流 FileUtils.openOutputStream(file);
The above is the detailed content of Application example tutorial of FileUtils class. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

Notes deleted from Xiaohongshu cannot be recovered. As a knowledge sharing and shopping platform, Xiaohongshu provides users with the function of recording notes and collecting useful information. According to Xiaohongshu’s official statement, deleted notes cannot be recovered. The Xiaohongshu platform does not provide a dedicated note recovery function. This means that once a note is deleted in Xiaohongshu, whether it is accidentally deleted or for other reasons, it is generally impossible to retrieve the deleted content from the platform. If you encounter special circumstances, you can try to contact Xiaohongshu’s customer service team to see if they can help solve the problem.

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of "What to do if the notes published by Xiaohongshu are missing" and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click "Me" → "Publish" → "All Publications" to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

Link AppleNotes on iPhone using the Add Link feature. Notes: You can only create links between Apple Notes on iPhone if you have iOS17 installed. Open the Notes app on your iPhone. Now, open the note where you want to add the link. You can also choose to create a new note. Click anywhere on the screen. This will show you a menu. Click the arrow on the right to see the "Add link" option. click it. Now you can type the name of the note or the web page URL. Then, click Done in the upper right corner and the added link will appear in the note. If you want to add a link to a word, just double-click the word to select it, select "Add Link" and press

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

As a lifestyle sharing platform, Xiaohongshu covers notes in various fields such as food, travel, and beauty. Many users want to share their notes on Xiaohongshu but don’t know how to do it. In this article, we will detail the process of posting notes on Xiaohongshu and explore how to block specific users on the platform. 1. How to publish notes tutorial on Xiaohongshu? 1. Register and log in: First, you need to download the Xiaohongshu APP on your mobile phone and complete the registration and login. It is very important to complete your personal information in the personal center. By uploading your avatar, filling in your nickname and personal introduction, you can make it easier for other users to understand your information, and also help them pay better attention to your notes. 3. Select the publishing channel: At the bottom of the homepage, click the "Send Notes" button and select the channel you want to publish.

In 2022, Apple added a new feature to the Notes app on iPhone and iPad that allows you to quickly scan printed or handwritten text and save it in a digital text format. Read on to learn how it works. On earlier versions of iOS and iPadOS, scanning text into Apple's Notes app required tapping the note's text field and then tapping the "Live Text" option in the pop-up menu. However, Apple is making it easier to digitize real-world notes in 2022. The following steps show you how to do this on a device running iOS 15.4 or iPadOS 15.4 and above. On your iPhone or iPad, open "

Most people write down everything, including recipes, birthdays, song lyrics, and more. on their iPhone’s Notes app. But many iPhone users reported that they deleted very important notes on their iPhone by mistake and now they are very nervous and frustrated. They don't know how to restore it on iPhone. We have done a lot of research on the matter and found two methods to recover deleted notes from iPhone. In this article, we will explain these two methods with which you can easily get back deleted notes. How to Recover Deleted Notes via Notes App Step 1: You should first launch the Notes app from the home screen on your iPhone. Step 2: Launch the Notes application
