No matter what language you learn, you will inevitably have access to the file system, often with documents. Java of course is no exception, some netizens feel IO design is very cumbersome, sometimes I also have this feeling, its practical proficiency, it is very convenient to think this thing. Before introducing Java IO, first introduce a very important class file.
After seeing the name of this class you must think that it represents a file, in fact it is not accurate, because the file class in Java can represent files or directories. This is illustrated in API Doc, and the file is represented by an abstract pathname. But do you think the catalogue is not a special document?
The use of file is very simple, and it has four constructors:
File(String parent,String child)
File(File parent,String child)
File(URI uri)
File(String pathname)
The first two of them allow us to create a new file or directory in a known-specific directory, and then we can create a new file or directory by pathname or URI. One thing to note, though, is that file is a system-independent representation, but the pathname representation is related to the system, such as "/" under UNIX, which is usually represented by a disk character under Windows. For example, absolute path C:\helloworld\mingjava, if the relative path is not the "/" Start, the general relative path is relative to the current directory. When we create a file, we can use the exists () method to determine if it exists, and if not, we can choose whether to create as a file or to create a directory. For example
File file = new File("hehe");
if(!file.exists())
{
file.mkdir();
}
for(int i=0;i <5;i++)
{
File listFile = new File(nextFile,"ming"+i+".txt");
if(!listFile.exists())
{
listFile.createNewFile();
}
}
If we already know a file object and want to create a new one under his directory, we can use the first constructor. Like what
File nextFile = new File(file,"ming\\hehe");
if(!nextFile.exists())
{
nextFile.mkdirs();
}
Note the mkdirs () is used when creating a multi-tiered directory. We can also enumerate a list of files in a directory, using the list () method to get an array of string[] types, which is the name of the file under the directory.
String[] list = nextFile.list();
for(int j = 0;j<list.length;j++)
{
System.out.println(list[j]);
}