Java Content Carding (17) API Learning (5) Files

Keywords: Java Eclipse jvm less

1. The Construction Method of File Class

(1) The role of File classes

Representing a file or directory with an object of the File class

(2)File(String path)

Create a File object by specifying the path of a file or directory

Path: It can be either a relative path or an absolute path.

For example: File noteFile = new File("note.txt");

System.out.println( file.exists() );

Interpretation:

Relative paths in java: The reference is the path where the JVM is started

When running Java programs through Eclipse, the relative path reference is: Engineering directory

 

The current project catalogue will be used as a reference, that is, note.txt will output true in the current project catalogue.

(3)File(URI uri)

uri: Unified Resource Location Identification

Get URI: Any class name. class.getResource("/abstract path"). toURI()

Search the specified subpath under the classpath environment variable to get the URL object converted to the URI object by the toURI method

Be careful:

You need to start with "/", which represents the classpath path path

Effect:

Customizable search lookup paths, i.e. adding classpath paths without modifying the program

For example:

File uri_File =new File( PathDemo.class.getResource("/res/uri-demo.txt").toURI() );

System.out.println( uri_File.exists() );

Interpretation: The first / representative is the classpath path path path

The classpath path path in eclipse is the src or bin directory under the project file, and res represents the package name, so you can find the file.

2. Common methods of File classes

(1) File class operation file

createNewFile: When the file represented by the file object does not exist, a new file can be created successfully, otherwise it will have no effect.

Delete: delete immediately

deleteOnExit: Delete when the program exits normally

Existence of exists

isFile determines whether it is a file and returns false if the file object does not already exist on disk.

length Gets File Size

getName Gets Files

GettAbsolutePath Gets the Absolute Path

(2) File class operation directory

mkdir: Only one layer of directory can be created. If there are multiple layers, the creation fails.

mkdirs: Single or multiple directories can be created

delete: delete empty directories

Determine whether the directory exists:exists

Determine if the directory is a directory: isDirectory returns false when the directory does not exist?

Get a list of directory contents:

list()

String[] f = file.list(); // Returns all file and directory names in the directory

listFiles()

File[] f = file.listFiles();//Return all files and directories in the directory

listFiles( FileFilter filter )

File[]  f = file.listFiles( new FileFilter(){ //File filters, screening out files and directories that meet their own requirements
        public boolean accept(File f){
                String fileName = f.getName();
                if(fileName.toLowerCase().startsWith("a")){
                         return true;
                }
                 return false;
       }
} );

(3) Examples: How to delete all directories and files in a non-empty directory

package file;

import java.io.File;

public class FileOprater {
	
	/**
	 * How to delete all directories and files in a non-empty directory
	 */
	public static void removeFile(File file) {
		/**
		 * file Either blank or file is not a directory, which does not fit the title.
		 */
		if(file == null || !(file.isDirectory())) {
			throw new RuntimeException(file+"Not a valid directory");
		}
		
		File[] files =  file.listFiles();
		for(File f : files) {
			if(f.isFile()) {//If f is a file, delete it directly
				f.delete();
			}else {
				removeFile(f);
			}
		}
		file.delete();//Delete empty directories recursively returned
	}
	
	public static void main(String[] args) {
		File file = new File("src/a");
		removeFile(file);
	}
}

3. Random AccessFile Class: Provides the ability to read and write the contents of files randomly (to read content anywhere in the file)

(1) Construction method

RandomAccessFile(File file, String mode)

RandomAccessFile(String name, String mode)

name:File path to access

mode:What model to start with "r" / "w" / "rw"

(2) File pointer

When the object is currently newly created, the file pointer of the object defaults to the first byte.

The function of the file pointer: to mark the location of the next read-write occurrence

See: Move the file pointer to the file header and jump back to the specified number of bytes

SkpBytes: Jump back the specified number of bytes from the current file pointer

readXxx

writeXxx

(3) Examples: video encryption

package file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class CodeMP4 {
	public static void main(String[] args){
	
		try {
			//Encrypted Video Files
			File file = new File("C:\\Users\\sun changxin\\Desktop\\abc.mp4");
			RandomAccessFile raf = new RandomAccessFile(file, "rw");
			
			//Number of bytes to get the file
			long len = raf.length();
			//Set the location of the variable record file pointer
			long filePointerPOS = 0;
			//Read 8k bytes at a time
			byte[] datas = new byte[8*1024];
			do {
				
				//First determine whether the file is larger than 8k, read 8K data to datas if it is larger, and change the datas array if it is less than 8k.
				if( len - filePointerPOS < datas.length ) {
					datas = new byte[ (int)(len - filePointerPOS) ];
				}
				//Read the data from the file, read the full data array, and put it into the array data
				raf.readFully(datas);
				filePointerPOS =  raf.getFilePointer();
				
				//Modify each number in the data array
				for( int i=0;i<datas.length;i++ ) {
					 datas[i] -= 1;//encryption
				}
				
				//Overlay that piece of data in the file with the modified datas array
				raf.seek(filePointerPOS - datas.length);
				raf.write(datas);
				
			}while( raf.getFilePointer() < len );
			
			raf.close();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

 

 

 

 

 

 

 

 

 

Posted by manimoor on Sat, 11 May 2019 05:03:17 -0700