Level 1: Create a file
related tasks
how to create the file
We know that Java
everything in Java is an object, so what is used to manipulate files should also be an object, which is a class, and classes are used to manipulate files File
in Java .File
How to create a file? Very simple, let's look at an example:
Use the above code to D
create a file under the disk helloworld.txt
.
How to tell if a file exists
If a file already exists, then we generally should not create it, so we need to know whether the file exists, how to judge?
Run the above code, if it D://helloworld.txt
already exists, it will output true
, otherwise it will output false
;
programming requirements
Begin - End
Please read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:
src/output
Created under the directory ,hello.txt
filetest.txt
.
It needs to be created first test.txt
and created later hello.txt
.
Note: File operations have exceptions that need to be thrown.
Tips: The representation of the file directory in the windows system is D://XX.XX, and the representation of the file directory in Linux is /xxdir/filename.txt. The Linux environment is used in the platform, so the code should be written It is time to use the Linux directory method.
package step1;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Scanner;
public class Task {
/********* Begin *********/
public void solution(){
try{
File file=new File("src/output/test.txt");
if(file.exists()==false){
file.createNewFile();
//System.out.println("Success!");
}
}catch (IOException e){
e.printStackTrace();
}
try{
File file=new File("src/output/hello.txt");
if(file.exists()==false){
file.createNewFile();
//System.out.println("Success!");
}
}catch (IOException e){
e.printStackTrace();
}
/********* End *********/
}
}
Level 2: Common operations on files
related information
create folder
This code will D
create a hello
folder under the disk.
Delete Files
This code can delete the file D
under the diskhelloworld.txt
List files in a folder
If we want to develop a file viewer, then we need to be able to view all files in the specified folder; Java
this method is provided in .
Example:
D
The files under the disk hello
folder are as follows:
Write the following code:
Output result:
a.txt
b.txt
text.txt
It can be found that Java
the folder in the folder is also an File
object. listFiles()
The method can be used to obtain the array of all files in the folder, and getName()
the method can be used to obtain the file name of the file.
programming requirements
Begin - End
Please read the code on the right carefully, and supplement the code in the area according to the prompts in the method to list all file information under the folder, delete the specified folder, and create a file under the folder. The specific requirements are as follows :
-
src/
Create foldertest2
folder under; -
Delete the file
src/output/
undertest2.txt
; -
src/test2/
Createhelloworld.txt
files and files under the directorystep2.txt
; -
Sort
src/output/
the directory andsrc/test2/
the file names of all files under the directory in ascending order and print to the console. -
Tip: You can use the Arrays.sort() function to sort, and you need to import the methods in the Arrays class: import java.util.Arrays.
package step2; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Arrays; public class Task { public static void dcFile() throws IOException { /********* Begin *********/ File file1=new File("src/test2"); file1.mkdir(); File filed=new File("src/output/test2.txt"); filed.delete(); File file2=new File("src/test2/helloworld.txt"); file2.createNewFile(); File file3=new File("src/test2/step2.txt"); file3.createNewFile(); System.out.println("output目录结构为:"); File dir1=new File("src/output"); File[]files1=dir1.listFiles(); String []n1=new String[5]; int i=0; for(File file:files1){ n1[i++]=file.getName(); //System.out.println(n1[i-1]); } Arrays.sort(n1); for(int num1=0;num1<i;num1++){ System.out.println(n1[num1]); } System.out.println("test2目录结构为:"); File dir2=new File("src/test2"); File[]files2=dir2.listFiles(); for(File file:files2){ System.out.println(file.getName()); } /********* End *********/ } }
Level 3: File Viewer
related information
isDirectory()
Methods can be used to determine File
whether an object is a folder.
Example:
If D://hello
it is a folder, output it true
.
programming requirements
Begin - End
Please read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:
- Realize the display of the directory structure of the given folder, and print to the console in the form of file names sorted in ascending order . If it is a folder, add it before its name
+--
, and if it is a file, add it--
. The upper-level directory and the lower-level directory, and the lower-level file are separated by two spaces , and the functions in the code area on the right are supplementedshowDirStructure(File dir)
to achieve the required functions. Among them, the function parameters The meaning is as follows:
1). dir
: Specify the folder to be displayed.
Note : main
For functions, you can click the folder in the upper right corner to switch to Test.java
the file of this level for viewing.
package step3;
import java.io.File;
import java.util.Arrays;
public class Task {
/********** Begin **********/
int n=1; //缩进层数
public void showDirStructure(File file) {
System.out.println("+--"+file.getName());
File[] dir = file.listFiles();
Arrays.sort(dir); // 按字母顺序给文件名排序
for(File files:dir)
{
if(files.isDirectory())
{
for(int i=0;i<n*2;++i) System.out.print(" ");
++n; //是文件夹,缩进2个空格
showDirStructure(files);
--n; //递归完成后返回上一层缩进。
}
else
{
for(int i=0;i<n*2;++i) System.out.print(" ");
System.out.println("--"+files.getName());
}
}
}
/********** End **********/
}
Level 4: Image Viewer
related information
file filter
.SYS
To exclude all files with extension from the list , we can FileFilter
do so using a file filter represented by an instance of the functional interface.
It contains a accept()
method which will File
take list as argument and return if the file should be listed true
. returns false
will not list the files.
The following code creates a file filter that will filter .SYS
files with the extension .
FileFilter filter = file -> {
if (file.isFile()) {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith(".sys")) {
return false;
}
}
return true;
};
The following code shows how to use a filter:
import java.io.File;
import java.io.FileFilter;
public class Main {
public static void main(String[] args) {
String dirPath = "C:\\";
File dir = new File(dirPath);
// Create a file filter to exclude any .SYS file
FileFilter filter = file -> {
if (file.isFile()) {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith(".sys")) {
return false;
}
}
return true;
};
File[] list = dir.listFiles(filter);
for (File f : list) {
if (f.isFile()) {
System.out.println(f.getPath() + " (File)");
} else if (f.isDirectory()) {
System.out.println(f.getPath() + " (Directory)");
}
}
}
}
File Directory:
File directory printed after filtering:
programming requirements
Begin - End
Please read the code on the right carefully, and supplement the code in the area according to the prompts in the method . The specific tasks are as follows:
- Realize the display of the directory structure of the given folder, and print to the console in the form of file names sorted in ascending order. If it is a folder, add it before its name
+--
, and if it is a file, add it--
. The upper-level directory and the lower-level directory, and the lower-level files are separated by two spaces . In addition, the files need to be filtered to only display files of image type. This level requires The image file types to be filtered are:“jpg,png,bmp”
, please completeshowDirStructure(File file)
the functions in the code area on the right to realize the functions required by this level, and the meanings of the function parameters are as follows:
file
: Specifies the folder to display.
package step4;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
public class Task {
/********** Begin **********/
public void showDirStructure(File file) {
if(file.isDirectory()){
System.out.println("+--"+file.getName());
}
int Blank = 2;
showDir(file,Blank);
}
public static void showDir(File file,int Blank){
File[] files = file.listFiles();
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
for (int k = 0; k < Blank; k++) {
System.out.print(" ");
}
System.out.println("+--" + files[i].getName());
showDir(files[i], Blank+2);
}
else {
int end = files[i].toString().indexOf(".");
String suffix = files[i].toString().substring(end+1);
if(suffix.equals("jpg") || suffix.equals("png") || suffix.equals("bmp")) {
for (int k = 0; k < Blank; k++) {
System.out.print(" ");
}
System.out.println("--" + files[i].getName());
}
}
}
}
/********** End **********/
}