Java file Operations

Source: Internet
Author: User

Before summing up the file operation, the first reprint of an article is about the size of the file and the difference between the space occupied by the file.

Windows operating system for disk paging management, the minimum paging size is 4kb, that is, if your hard disk assumes 100GB, then the number of your paging is: (100x1000x1000)/4,
Of course, you put a character, only 1 bytes, but he wants to allocate to a space, and this space can be loaded with a page size, then because the minimum paging size is 4KB, so the hint takes up space of 4kb, the actual size occupies a byte
Check your hard disk for an arbitrary non-empty directory or the properties of non-empty files, see the size of 2 values: A file size, that is, the size of the file, the other is called space, is occupied by the hard disk space.
Occupy space must be greater than or equal to the file size, because the smallest unit of the hard disk is a cluster, any file is no smaller than a cluster, the default disk cluster is generally 4KB.

You can think of a hard disk as a dock
There are several warehouses in the warehouse, and there are many boxes for the files.
Dock: Equivalent to the entire hard disk
Warehouse: partition equivalent to Hard disk (c:d: E:), strictly speaking logical partition, because there are extended partitions
Box: equivalent to cluster (cluster, minimum storage unit)
File: equivalent to. txt.rar. *. *, etc.
different file storage methods (Fat16,fat32, NTFS) determine the size of the box:
Generally speaking, file storage method requirements:
Small Warehouse with small box file
Large warehouse with large box file
A file can be loaded into a different box
Two files cannot be in the same box
Why two files cannot be placed in the same box? The
personal understanding is that it is difficult to find (address) a file if it is loaded in the same box.
about sector (partition), track (tracks) and so on are used to implement the box, do not go to the bottom of the
such as FAT32:
8GB below the warehouse (partition), the size of the box 4kB
8GB~16GB Warehouse, the size of the box is 8kB
16GB~32GB Warehouse, the size of the box is 16kB
more than 32GB warehouse, the size of the box is 32kB
If it is 8GB below the partition:
such as the landlord's file size is only 1 bytes, but to exclusive a box,
therefore will occupy 4kB.
There may also be people who ask, my partition is 40GB
How 1 bytes of file also accounts for 4kB, why not 32kB
This is because you are very smart, you may be using the NTFS file storage method.
NTFS stipulates:
The warehouse (partition) below 1GB, the box size is 2kB
1GB above the warehouse, the box size is 4kB
2TB (2 x 1024GB) above this I do not know the size of the box
to give an example:
For example, hard disk partition (NTFS) 1GB or more:
If the file size is 5kB
file to two boxes to install, so to account for 8kB
View file properties, you will see:
File size is 5kB
and occupy space (the capacity of several boxes) is 8kB
Others will ask:
Does disk grooming (defrag) increase the free space on your hard disk? The
answer is no.
because the cause of disk consolidation is the case of the east of the box, put a
to find the file is slow, disk collation just put the box together
easy to find, improve disk access speed
So how to increase the disk free space?

One way to do this is to compress the file. Previously Win98 seemed to have a tool for compressing disk space.

I. Structure arrangement of this article

Understanding the file class needs to be seen from the following perspectives

Functions and constants of the 1:file class

2: How to use the file class, such as adding and deleting changes.

3: What do I need to pay attention to using the file class? System differences, coding, efficiency, security encryption, document retrieval and management

Ii. Introduction of File

11.3.1 file Operations

File is one of the most common data sources, in the program often need to store data into files, such as file, sound files and other data files, also often need to be required to read from the specified file data. Of course, in the actual use, the file contains a format, this format requires programmers to design according to needs, read the existing files also need to be familiar with the corresponding file format, in order to get the data from the file correctly read out.

There are many storage media for files, such as hard disks, CDs, and USB drives, since the IO class design, the operation of converting from a data source to a stream object is implemented by the API, so the difference between storage media is transparent to the programmer, regardless of the actual writing code.

The concept of the 11.3.1.1 file

A file is a basic form of data storage in a computer, and it is a good choice to use a file as a persistent data store if the data is not read and written at a very high speed and the amount of data stored is not very large when the data is actually stored.

The data stored inside the file is different from the in-memory data, and the data that is saved in the file is a "persistent store", that is, when the program exits or the computer shuts down, the data is still there, and the data inside the memory is lost after the program exits or the computer shuts down.

In different storage media, the data in the file is stored in a certain order, in the actual read by the hardware and the operating system to complete the control of the data to ensure that the program reads the data and the order of storage consistent.

Each file is represented by a file path and file name, and when the file needs to be accessed, you only need to know the path to the file and the full name of the file. In different operating system environments, file path representations are not the same, for example, the general representation in the Windows operating system is C:\windows\system, while the Representation on UNIX is/user/my. So if you need to allow Java programs to run under different operating systems, you need to be more careful when writing file paths.

11.3.1.1.1 absolute path and relative path

An absolute path is the full path to a written file, such as D:\java\Hello.java, which contains the full path of the file D:\java and the full name of the file Hello.java. Using this path, you can find only one file without ambiguity. However, the use of absolute paths in representing files is very restrictive and cannot be run under different operating systems because absolute paths are expressed differently under different operating systems.

A relative path is a partial path to a written file, such as \test\hello.java, which contains only part of the path to the file \test and the full name of the file Hello.java, some of which are sub-paths under the current path, such as the current program running under D:\ABC. Then the full path to the file is d:\abc\test. Using this form, you can more generally represent the location of the file, resulting in a certain degree of flexibility in the file path.

When you run a program in an Eclipse project, the current path is the root of the project, such as when the workspace is stored in D:\javaproject and the current project name is Test, the current path is: d:\javaproject\Test (the current path includes the name of the current project). When running a program under the console, the current path is the directory where the class file resides, and if the class file contains the package name, the package name at the top of the class file is the current path.

Note: Here after the measurement, the relative path should be Test\hello.java, is from the current project path, if preceded by a backslash, it becomes the root directory, such as \test\hello.java is not d:\javaproject\Test\test\ Hello.java, but D:\ Test\hello.java, this should be noted.

In addition, when writing file paths inside the Java language code, you need to be aware of case, case, and capitalization, and the folder names in the path are case sensitive. Because ' \ ' is a special character in the Java language, writing a file path inside the code, such as "C:\test\java\Hello.java", is required to be written as "C:\\test\\java\\hello.java" or "c:/test/ Java/hello.java ", these need to be noted in the code.

11.3.1.1.2 file name

File names are generally named by "filename. Suffix name", where "file name" is used to denote the role of the file, and the suffix name is used to represent the type of the file, which is a common form of the current operating system, such as "Readme.txt" file, where the readme represents the file, While the TXT suffix name means that the file is a text file type, in the operating system, it also automatically associates a specific format suffix name with the corresponding program, which is opened with a specific program when double-clicking the file.

In fact, the file name is just a sign, and the actual storage of the contents of the file is not necessarily linked, just use this way to facilitate the use of files. When you need to store data in your program, you can customize the file's suffix name to indicate your file type if you have designed a specific file format.

As with the file path, the file name is also case-sensitive when written inside Java code, and the case of the file name must match the case in the operating system.

Also, do not forget to write the file's suffix when writing the file name.

11.3.1.2 File class

In order to conveniently represent the concept of the file and to store some basic operations for the file, a specialized class--file class is designed in the java.io package.

The file class contains a functional method for most of the files, and the object of the class can represent a specific file or folder, so it has been suggested that the class name of the class be modified to filepath, because the class can also represent a folder, or more precisely a file path.

The basic use of the file class is described below.

1. File object represents path

The object of the file class can represent a specific file path and, when actually represented, you can use an absolute path or a relative path.

The following is an example of a file object created.

Public File (String pathname)

In this example, a file path is used to represent an object of the files class, for example:

File F1 = new file ("D:\\test\\1.txt");

File F2 = new file ("1.txt");

File F3 = new file ("E:\\abc");

The F1 and F2 objects here represent a file, F1 is an absolute path, and F2 is a relative path, F3 represents a folder, and a folder is also a file path.

Public File (string parent, String child)

You can also use the parent and child paths together to implement a file path, for example:

File F4 = new file ("d:\\test\\", "1.txt");

The file path represented by this is: D:\test\1.txt.

2. File class Common methods

The file class contains a lot of methods to get the properties of files or folders, which is convenient to use, and the following common methods are described below:

A, CreateNewFile method

public Boolean CreateNewFile () throws IOException

The function of this method is to create the specified file. This method can only be used to create a file, cannot be used to create a folder, and the folder contained in the file path must exist.

B, Delete method

public Boolean Delete ()

The function of this method is to delete the current file or folder. If you delete a folder, the folder must be empty. If you need to delete a non-empty folder, you need to first delete each file and folder inside the folder, and then can be deleted, this need to write a certain logical code implementation.

C, Exists method

public Boolean exists ()

The purpose of this method is to determine whether the current file or folder exists.

D, GetAbsolutePath method

Public String GetAbsolutePath ()

The function of this method is to get the absolute path of the current file or folder. For example, c:\test\1.t returns c:\test\1.t.

E, GetName method

Public String GetName ()

The function of this method is to get the name of the current file or folder. For example, c:\test\1.t returns 1.t.

F, GetParent method

Public String getParent ()

The function of this method is to get the parent path in the current path. For example, c:\test\1.t returns C:\Test.

G, Isdirectory method

public boolean isdirectory ()

The function of this method is to determine whether the current file object is a directory.

H, Isfile method

public boolean isfile ()

The function of this method is to determine whether the current file object is a document.

I, Length method

public long Length ()

The function of this method is to return the number of bytes that are consumed when the file is stored. This value obtains the actual size of the file, not the amount of space the file occupies when it is stored.

J, List method

Public string[] List ()

The function of this method is to return all filenames and folder names under the current folder. Description, the name is not an absolute path.

K, Listfiles method

Public file[] Listfiles ()

The function of this method is to return all the file objects under the current folder.

L, mkdir method

public boolean mkdir ()

The purpose of this method is to create the current file folder without creating other folders in that path. Assuming that there is only one Test folder under the D disk, the creation of the D:\test\abc folder succeeds, and if you create the d:\a\b folder, the creation fails because the D:\a folder does not exist in that path. Returns true if the creation succeeds, otherwise false.

M, Mkdirs method

public boolean mkdirs ()

The purpose of this method is to create a folder that is automatically created if the parent directory contained in the current path does not exist.

N, Renameto method

public boolean Renameto (File dest)

The function of this method is to modify the file name. The file path cannot be changed while the file name is being modified, and if it is already in the path, the modification fails.

O, Setreadonly method

public boolean setreadonly ()

The function of this method is to set the current file or folder to read-only.

Basic example:

Stringfilepath= "\\ex\\rx\\rea.txt";//or/ex/Rx/rea.txt

int lastindex=filepath.lastindexof ("\ \");//or

if (lastindex>0)

{

String dir=filepath.substring (0,lastindex+1);

File d=new file (dir);//If this is filepath, Rea.txt will be created as a path, and the following will naturally take filepath as the path

if (!d.exists ())

D.mkdirs ();

}

filefile=New File (FilePath);

if (!file.exists ())

{

File.createnewfile ();

}

System. out. println (File.getpath ());

System. out. println (File.getabsolutepath ());

System. out. println (File.getparent ());

System. out. println (File.getname ());

System. out. println (File.isfile ());

System. out. println (File.isdirectory ());

System. out. println (File.length ());

System. out. println ();

filefile2=New File ("\\ex");

File[]files=file2.listfiles ();

for (int i=0;i<files.length;i++)

{

System. out. println (Files[i].getname ());

System. out. println (Files[i].isdirectory ());

System. out. println ();

}

filefile4=New File ("\\ex\\ text document. txt");

filefile3=New File ("\\ex\\ new text document. txt");

boolean B=file4.renameto (FILE3);

System. out. println (b);

Output

\ex\rx\rea.txt =================== GetPath

D:\ex\rx\rea.txt =================== GetAbsolutePath

\ex\rx =================== getParent

Rea.txt =================== GetName

True =================== isfile

False =================== Isdirectory

0 =================== Length

Rx =================== GetName

True

Text document. txt

False

True =================== Renameto

Show or delete all files

Public Static void Printallfile (File f)

{

Print the current file name

System. out. println (F.getname ());

Whether it is a folder

if (F.isdirectory ())

{

Get all sub-files and subfolders under this folder

file[] F1 = F.listfiles ();

Cycle through each object

int len = f1.length;

for (int i = 0;i < len;i++)

{

recursive invocation, processing of each file object

Printallfile (F1[i]);

}

}

}

Public Static void DeleteAll (File f)

{

File

if (F.isfile ())

{

F.delete ();

}

Else

{//Folder

Get all sub-files and subfolders under the current folder

Filef1[] = F.listfiles ();

Cycle through each object

int len = f1.length;

for (int i = 0;i < len;i++)

{

recursive invocation, processing of each file object

DeleteAll (F1[i]);

}

Delete current Folder

F.delete ();

}

}

File read and write in IO Chapter

Java file Operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.