Java Old IO
File IO before JDK 7.0 is defined as old File IO, in contrast with the NIO.
In the old IO, the major concept is the File, and stream, reader/writer, buffer these facilities are used to wrap the File and achieve the extended functionalities.
IO File
In the old IO, both the path and file are represented by the File class; and service functionalities like delete(), createNewFile(), mkdir(), exist() are included in the File class. File stands for abstract File, it is not associated with a physical file or path. After the creation method is invoked, it is pointed to this physical file and path. When a File created corresponding to an existing file, then it is automatically associated with it, otherwise, the newly created File instance is just an abstraction.
File(String fileName)
File(String pathName)
File(String parentPath, String childPath)
File(File parent, String child)
File(File path, File fileName)
Types of File Data
Java IO handles two types of data, i.e. byte and character.
Byte: read or write 8-bit to or from the data source, mainly zip, image and PDF file.
Character: read or write 16-bit to or from the data source, mainly uni-code text file.
Types of File IO Handlers
Java IO handles input and out respectively:
For byte stream via FileInputStream and FileOutputStream.
For character stream via FileWriter and FileReader.
Buffered Streams
File IO uses the decorator pattern to manage how to extend File IO functionalities.
Java IO uses external Buffered Input/Output streams(byte) or Buffered Reader/Writer(char) to add the buffer functionalities on the existing byte IO or char IO.
Buffered streams are commonly used for achieving a better performance. Invoking system IO operation to read or write a single byte or character is not efficient. So, buffered IO was introduced. It stores byte or character to be read or written into a piece of memory space(buffer). When a buffer is full or empty, IO API is invoked, so that the buffered data can be handled like a batch job.
The following is a simple example that explains how to implement buffered stream operations.
public class BufferedStream {
public static void main(String[] args) throws IOException {
String content = "Java is verbose!";
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("my.txt"))) {
bos.write(content.getBytes());
bos.flush();
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter("my2.txt"))){
bw.write("Java has some improvements");
bw.flush();
}
}
}
Read and Write Byte to File
Abstract class InputStream and OutputStream its sub-implementations
FileInputStream, BufferedInputStream, DataInputStream, and ObjectInputStream FileOutputStream, BufferedOutputStream, DataOutputStream, and ObjectOutputStream
public class CopyPdfUsingStream {
public static void main(String[] args) {
String name = "billet.pdf";
String copy = "copyBillet.pdf";
try (
FileInputStream fis = new FileInputStream(name);
FileOutputStream fos = new FileOutputStream(copy);) {
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException ex) {
Logger.getLogger(CopyPdfUsingStream.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Java NIO
Path, Paths, Files are classes of Java NIO since Java 7. The Path is a replacement of File in the NIO. Paths is a utility providing static factory method to create Path objects. Files is another utility class, manipulating a File object.
Path Object
The Path is an Interface representing a directory or a file, but independent of a physical file system. Please note that Path is an abstraction of a file or directory.
Why we need an Abstraction of Path? It because the underlying OS has different directory delimiters or different directory roots like in Win OS and Unix OS.
Paths Class
Paths class creates a Path object.
Paths. get(String first, String... more);
FileSystem. getDeafault(). get(String first, String ... more)
The above is the most simple and straightforward way to create a Path object, for you don't need to worry about the separator format, forwarding slash or backwards slash.
Once Path object is created, it is system-dependent; and two Paths having the same attributes but
for the different OS, they are different Path object.
Path and File can be converted to each other.
Resolving a Path
path1 resolve path2: resolve path2 within path1's directory, meaning that joining path2 on the top of path1. joining a relative path on the top of an absolute path; or joining a relative path on the top of another relative path; joining an absolute path on the top of a relative path, doesn't make sense, because an absolute path doesn't depend on any other path, so java will return the absolute path again.
Relativizing a Path
path1 revitalize path2: give me a path that shows how to get from path1 to path2, meaning that finding out the difference between the two paths. relativizing an absolute path to a relative path, or relativizing two relative paths.
Files Class
Files offer static methods to operate a Path instance, like determine existence, copy, delete and moving around.
Files.exists(Path) and Files.notExists(Path)
Files.copy(sourcePath, targetPath): if source is not existed, it throws FileNotExistedException; if the targetPath is already existed, it throws FileExistedException.
File Attributes
You use the file to store data and OS store additional data about your data about creation, modification and accessing so on. You can get individual attribute, or access a group of attributes so as to improve the performance.
Accessing individual attributes
Files class defines static methods to access individual attributes.
Files.size(path)
Files.isDirectory(path)
Files.isHidden(path)
Files.getLastModifiedTime(path)
Files.isReadable(path)
Files.isWritable(path)
Files.isExecutable(path)
Files.isSameFile(path)
or
Using Files class getAttributes(String nameOfAttribute)
Modifying file/directory attributes
using Files class static methods
Set the value of a file attribute
Path setAttribute(Path path, String attribute, Object value, LinOption ...options)
Updates a file's last modification time
Path setLastModificationTime(Path path, FileTime time)
Updates the file owner
Path setOwner(Path path, UserPrincipal owner)
Accessing group attributes
Instead of accessing individual attributes, you may access a group of attributes. In this way, it may improve accessing performance.
Attributes are classified as groups, for different file systems may offer different attributes. An interface represents a group of attributes.
There are two types of attribute groups, one is for reading attributes, another is for modifying attributes.
The term “View” are collectively referred to as the view interfaces, and they’re used to update file and directory attributes. The interface without “View” is used to read out the attributes.
- BasicFileAttributes and BasicFileAttributeView: all file attributes supported by all OS.
- DosFileAttributes and DosFileAttributeView: DosFileAttributes extends BasicFileAttributes, it defines file attributes supported by DOS.
- PosixFileAttributes and PosixFileAttributeView: PosixFileAttributes extends BasicFileAttributes, it defines file attributes supported by UNIX.
- AclFileAttributeView: exitends form FileOwnerAttributeView; only for the Windows OS; handling file permissions
- FileOwnerAttributeView: get owner and set Owner.
- UserDefinedFileAttributeView: access or modify user-defined attributes to a file or directory; for instance, setting a File/directory a delete attribute, later on removing them collectively.
Reading attributes:
As reading file/directory attributes, providing the class type of target interface.
DosFileAttributes dosFileAttributes = Files.readAttributes(path, DosFileAttributes.class);
System.out.printf("DosFileAttributes: isArchive? %b \n ", dosFileAttributes.isArchive());
System.out.printf("DosFileAttributes: isSystem? %b \n ", dosFileAttributes.isSystem());
static Map<String,Object> readAttributes(Path path, String attributes, LinkOption... options)
throws IOException
attributes: it can take values basic, dos, and posix. If this value is absent, it defaults to basic. You can specify * to read all the attributes for a group.
Updating attributes
if you want to modify file attributes, then achieving view instance first. Afterwards, via the view, you may reset the attributes.
//BasicFileAttributeView interface defines API to modify attributes
BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);
//basicFileAttributeView modify all timeStamps
long now = System.currentTimeMillis();
FileTime creationTime = FileTime.fromMillis(now);
FileTime accessTime = FileTime.fromMillis(now - 1000);
FileTime modifyTime = FileTime.fromMillis(now - 2000);
view.setTimes(creationTime, accessTime, modifyTime);
No comments:
Post a Comment