Java IO series:

  1. First, sort out the huge Java IO system
  2. Path, Files, RondomAccessFile
  3. Serialization and deserialization

The File type

The File class introduced in JDK1.0, in the java.io package of the Java language, provides the File class to describe the operation and management methods of files and directories. The File class is not a subclass of InputStream, OutputStream, or Reader, Writer, because it is not responsible for data input and output, but for managing disk files and directories

Note: The File class can only manipulate the properties of a File, not the contents of a File.

However, the Path and Files classes added in Java7 are more convenient to use than File class, File class online tutorial is also more, so, here is not more introduction to File class, directly on the more hard dishes. The Path and Files


The Path class

First, build the Path class

The Path class is created primarily with the Help of the Paths class.

1. Paths.get()

// java.nio.file.Paths:

static Path get(String first, String... more);
Copy the code

The static paths.get () method takes one or more strings, concatenates them with the path delimiters of the default file system (unix-like file systems are /, Windows is \), and parses their results.

If it does not represent a valid path to a given file system, an InvalidPathException is thrown.

Use cases (unix-like environment):

// Absolute path
Path absolute = Paths.get("/home"."harry");
// Relative path
Path relative = Paths.get("myprog"."conf"."user.properties");

// Get a single string containing multiple parts
String baseDir = props.getProperty("base.dir");
Path basePath = Paths.get(baseDir);
Copy the code

2. path1.resolve(path2)

// java.nio.file.Path

Path resolve(Path other);
Path resolve(String other);
Copy the code

Used to combine or resolve paths

  • If path2 is an absolute path, the result is path2
  • If no, path1 is followed by path2 according to the cabinet of the file system

3. path1.resolveSibling(path2)

// java.nio.file.Path

Path resolveSibling(Path other);
Path resolveSibling(String other);
Copy the code

This method produces siblings of a specified path by resolving its parent path.

For example: if workPath is /opt/myapp/work, then the following call

Path tempPath = workPath.resolveSibling("temp");

Create a Path to /opt/myapp/temp and assign it to tempPath.

Other apis for the Path class

// java.nio.file.Path

Path toAbsolutePath(a) // Return the absolute path equivalent to the path.
Path getParent(a) // Returns the parent path, or nu11 if the path has no parent.
Path getFileName(a) // Returns the last part of the path, or nu11 if there are no parts in the path.
Path getRoot(a) // Returns the root part of the path, or nu11 if the path has no root parts.
toFile(a) // Create a File object from the path.
Copy the code

Class Files

Simplify reading and writing Files through Files

// java.nio.file.Files

// Read the contents of the file.
static byte[] readAllBytes(Path path)
static List<String> readAllLines(Path path, Charset charset) 
// Write the given content into the file and return path.
static Path write(Path path, byte[] contents, OpenOption... options)
static Path write(Path path, Iterable<? extends CharSequence> contents, OpenOption options)
// Open a file for reading or writing out.
static InputStream newInputStream(Path path, OpenOption... options)
static OutputStream newoutputStream(Path path, OpenOption... options)
static BufferedReader newBufferedReader(Path path, Charset charset)
static BufferedWriter newBufferedWriter(Path path, Charset charset, OpenOption... options)
Copy the code

These shortcuts save you from having to deal with FileInputStream, FileOutputStream, BufferedReader, and BufferedWriter.

The simple methods of read and wirte are suitable for medium sized text files. If you are dealing with large files, or binary files, you should still use the well-known streams or readers/writers:

  • InputStream in = Files.newInputStream(path);
  • OutputStream out = Files.newOutputStream ( path );
  • Reader in = Files.newBufferedReader(path, charset);
  • Writer out = Files.newBufferedWriter(path, charset );

Create Files and directories using Files

// java.nio.file.Files

// Create a file or directory. The createDirectories method also creates all intermediate directories in the path.
static Path createFile(Path path, FileAttribute
       ... attrs)
static Path createDirectory(Path path, FileAttribute
       ... attrs)
static Path createDirectories ( Path path , FileAttribute
       ... attrs )

// Create a temporary file or directory in a location suitable for temporary files, or in a given parent directory. Returns the path to the file or directory that was created.
static Path createTempFile(String prefix, string suffix, FileAttribute
       ... attrs)
static Path createTempFile(Path parentDir, String prefix, String suffix, FileAttribute
       ... attrs)
static Path createTempDirectory ( String prefix, FileAttribute
       ... attrs)
static Path createTempDirectory(Path parentDir, String prefix, FileAttribute
       ... attrs)

Copy the code

Copy, move, and delete Files using Files

// java.nio.file.Files

// Copy or move from to the given location and return to.
static Path copy(Path from, Path to, CopyOption... options)
static Path move(Path from, Path to, CopyOption... options)

Return the number of bytes copied from the input stream to a file or from a file to the output stream.
static long copy(Inputstream from, Path to, CopyOption... options)
static long copy(Path from, OutputStream to, CopyOption... options)

// Delete the given file or empty directory. The first method throws an exception if a file or directory does not exist, while the second method returns false in that case.
static void delete(Path path)
static boolean deleteIfExists(Path path)

Copy the code

The list of standard options for file manipulation is as follows:

4. Obtain file information through Filse

//java.nio.file.Files

// Checks the given properties of the file specified by the path.
static boolean exists(Path path)
static boolean isHidden(Path path)
static boolean isReadable(Path path)
static boolean iswritable(Path path)
static boolean isExecutable(Path path)
static boolean isRegularFile(Path path)
static boolean isDirectory(Path path)
static boolean isSymbolicLink(Path path)
// Get the file size in bytes.
static long size(Path path)
// Read the file properties of type A.
A readAttributes ( Path path , Class<A> type , LinkOption ... options )
Copy the code

Through the Files. ReadAttributes (path, BasicFileAttributes. Class); Get the BasicFileAttributes object for the relevant path to invoke the following API

//java.nie.file.attribute.BasicFileAttributes

// Get the requested attribute.
FileTime creationTime(a)
FileTime lastAccessTime(a)
FileTime lastModifiedTime(a)
boolean isRegularFile(a)
boolean isDirectory(a)
boolean isSymbolicLink(a)
long size(a)
Object filekey(a)
Copy the code

V. Operation of other Files

Files also has some other operations, such as:

  • Access items in the directory
  • Using directory streams
  • .

Because these operations involve streams, and I don’t know about streams yet, I’m not going to teach you how to do this. If you are interested, you can check the API documentation on the official website.

RandomAccessFile class

RandomAccessFile

RandomAccessFile can either read the contents of a file or output data to a file. At the same time, RandomAccessFile supports “random access” mode, the program can jump directly to any part of the file to read and write data.

Since RandomAccessFile is free to access anywhere in the file, it is a better choice if you need to access parts of the file rather than read the file from beginning to end.

Unlike output streams such as OutputStream and Writer, RandomAccessFile allows you to define a pointer to a file record freely. So RandomAccessFile can append content to an existing file. If your program needs to append content to an existing file, you should use RandomAccessFile.

RandomAccessFile has many methods, but one of its biggest limitations is that it can only read and write to files, not to other IO nodes.

RandomAccessFile method

//java.io.RandomAccessFile

// constructor
RandomAccessFile(String file, String mode)
RandomAccessFile(File file, String mode)
// Returns the current position of the file pointer.
long getFilePointer(a)
// Set the file pointer to pos bytes from the beginning of the file.
void seek ( long pos )
// Returns the length of the file in bytes.
long length(a)
Copy the code

1. RandomAccessFile constructor

The RandomAccessFile class has two constructors, which are essentially the same except that they specify the form of the File – one requires the String argument to specify the filename, and the other uses the File argument to specify the File itself. In addition, when creating the RandomAccessFile object, you also need to specify a mode parameter that specifies the access mode for the RandomAccessFile. There are four modes.

**”r” : ** opens in read-only mode. Any call to write methods on the result object will cause IOException to be thrown. “Rw “: open for reading and writing. “RWS “: open for reading and writing. In contrast to “RW”, “RWS” also requires that every update to the “contents of a file” or “metadata” be written synchronously to the underlying storage device. “RWD” : opens for reading and writing, and in contrast to “RW”, “RWD” also requires that every update to the “contents of a file” be written synchronously to the underlying storage device.

2. RandomAccessFile important method

RandomAccessFile can read and write files, so it has both a read() method like InputStream and a write() method like OutputStream. In addition, RandomAccessFile has two unique methods to support its random-access nature.

When a program creates a new RandomAccessFile object, the file pointer to the object is located at the file header (0). After n bytes have been read/written, the file pointer will move n bytes. In addition, RandomAccessFile can freely move the record pointer. Here are two special methods RandomAccessFile has to manipulate record Pointers to achieve random access:

Long getFilePointer() : returns the current position of the file record pointer void seek(long pos) : locates the file record pointer to the pos position