In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of File and RandomAccessFile of Java Iamp O, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know about it.
Preface
The I / O system is the input / output system. For a programming language, it is not easy to create a good input / output system. Because there are not only a variety of Iamp O sources and receivers you want to communicate with (files, console, network links, etc.), but also need to support a variety of different ways of communication (sequential, random access, buffering, binary, character-by-character, line-by-line, word-by-word, etc.).
The designers of the Java class library solve this problem by creating a large number of classes, such as byte-oriented classes (byte stream, InputStream, OutputStream), character-oriented and Unicode-based classes (byte stream, Reader, Writer), nio classes (new Imaco, to improve performance and functionality), and so on. Therefore, we need to learn a considerable number of classes before we fully understand the Java Iamp O system in order to use it correctly. So it may be confusing at first that there are so many classes provided by the Java IMab O system, but after we have systematically combed through the whole Java I Weibo O system and integrated this part of the knowledge into our entire knowledge system, we can quickly eliminate this confusion.
In this topic, I will summarize the use of most of the Java-related classes, ranging from traditional Imax O such as: File, byte stream, character stream, serialization to the new I/O:nio. In this section, I will first summarize the relevant knowledge of File and RandomAccessFile in the following order:
1. File
1.1 File introduction to common methods
According to the official documentation, the File class in Java is an abstraction of file and directory paths, and users perform operations related to files or directories directly through File. My understanding is that the function of the File class is to refer to files or directories. Through the abstraction of File, we can easily manipulate files or directories without paying attention to the differences of the operating system. The official document describes it as follows:
An abstract representation of file and directory pathnames.
User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames.
The user interface and the operating system name files and directories through system-related pathnames. The File class provides an abstract, system-independent perspective to describe hierarchical pathnames. File stands for abstract pathname and consists of two parts:
An optional system-related prefix, such as the disk drive specifier (disk-drive specifier), is "/" in unix systems and "\" in windows systems
A sequence of 0 or more string names
With regard to the use of File, I think it would be more efficient to learn directly through examples:
Public class FileDemo {public static void main (String [] args) throws IOException {File dir = new File ("f:/dirDemo"); System.out.println ("dir exists:" + dir.exists ()); dir.mkdirs (); System.out.println ("dir exists:" + dir.exists ()); if (dir.isFile ()) {System.out.println ("dir is a file.");} else if (dir.isDirectory ()) {System.out.println ("dir is a directory") } File file = new File ("f:/dirDemo/fileDemo") System.out.println ("\ n Absolute path:" + file.getAbsolutePath () + "\ n Can read:" + file.canRead () + "\ n Can write:" + file.canWrite () + "\ ngetName:" + file.getName () + "\ ngetParent:" + file.getParent () + "\ ngetPath:" + file.getPath () + "\ nlength:" + file.length () + "\ nlastModified:" + file.lastModified () + "\ n isExist:" + file.exists () File.createNewFile (); System.out.println ("is file exist:" + file.exists ()); if (file.isFile ()) {System.out.println ("file is a file.");} else if (file.isDirectory ()) {System.out.println ("file is a directory");} System.out.println (); for (String filename: dir.list ()) {System.out.println (filename);}
Output result:
Dir exists: falsedir exists: truedir is a directoryAbsolute path: F:\ dirDemo\ fileDemoCan read: falseCan write: falsegetName: fileDemogetParent: F:\ dirDemogetPath: F:\ dirDemo\ fileDemolength: 0lastModified: 0isExist: falseis file exist: truefile is a file.fileDemo
In this simple demo, we use several different file feature query methods to display the information of the file or directory path:
GetAbsolutePath (), which gets the absolute path to a file or directory
CanRead (), canWrite (), whether the file is readable / writable
GetName (), get the file name
GetParent (), which gets the directory pathname of the parent level
GetPath (), get the file path name
Length (), file length
LastModified (), the last modification time of the file, and the timestamp returned
Exists (), whether the file exists
IsFile (), whether it is a file
IsDirectory (), whether it is a directory
Mkdirs (), create a directory, and create a directory that does not exist
CreateNewFile (), create a file
List (), which returns all File names in the directory as an array of characters
The exists () method returns whether a File instance exists, which means whether it exists on disk, not that the File instance exists in the virtual machine heap memory. An instance of the File class may represent an actual file system such as a file or directory, or it may have no practical meaning, just a File class with no associated actual file, and if not, exists () returns false.
1.2 File filter
The array returned by the list () method contains all the file names under this File. If you want to get a specified list, for example, if you want to get all the files with the extension .java, you can use a "directory filter" (which implements the FilenameFilter interface), in which you can specify how to display qualified File objects. We pass a self-implemented FilenameFilter into the list (FilenameFilter filter) method, override its accept () method in the FilenameFilter as a parameter, and specify the logic we want, which is actually the embodiment of the policy pattern.
For example, all we need to do is to get the xml file in the current project and directory:
Public class XmlList {public static void main (final String [] args) {File file = new File ("."); String list;list = file.list (new FilenameFilter () {@ Overridepublic boolean accept (File dir, String name) {Pattern pattern = Pattern.compile ("(. *)\\ .xml"); return pattern.matcher (name). Matches ();}}); Arrays.sort (list,String.CASE_INSENSITIVE_ORDER); for (String dirItem: list) System.out.println (dirItem);}}
In this example, we pass parameters to list () using an anonymous inner class. Inside the accept () method, we specify a regular filtering strategy. When we call the list () method of File, we automatically call the accept () method for each file name under this directory object to determine whether to include the file. The result is represented by the Boolean value returned by accept ().
The above is only a list of some methods that I think are more commonly used in the File class, and it is only a part of it. For more details, please refer to the official documentation.
1.3 Catalog tools
Next, let's take a look at a utility that can get all or meet the required File collections in a specified directory:
The public class Directory {/ / local method can get the collection of specified files in the specified directory public static File [] local (File dir,String regex) {return dir.listFiles (new FilenameFilter () {private Pattern pattern = Pattern.compile (regex); @ Overridepublic boolean accept (File dir,String name) {return pattern.matcher (new File (name). GetName ()). Matches ();}} public static File [] local (String dir,String regex) {return local (new File (dir), regex) } / / walk () method can obtain all files or directories that meet the requirements under the specified directory, including public static TreeInfo walk (String start,String regex) {return recurseDirs (new File (start), regex);} public static TreeInfo walk (File start,String regex) {return recurseDirs (start,regex);} public static TreeInfo walk (String start) {return recurseDirs (new File (start), ". *");} public static TreeInfo walk (File start) {return recurseDirs (start, ". *") } static TreeInfo recurseDirs (File startDir,String regex) {TreeInfo treeInfo = new TreeInfo (); for (File item: startDir.listFiles ()) {if (item.isDirectory ()) {treeInfo.dirs.add (item); treeInfo.addAll (recurseDirs (item,regex));} else {if (item.getName (). Matches (regex)) treeInfo.files.add (item);} return treeInfo;} public static class TreeInfo implements Iterable {public List files = new ArrayList (); public List dirs = new ArrayList () @ Overridepublic Iterator iterator () {return files.iterator ();} void addAll (TreeInfo other) {files.addAll (other.files); dirs.addAll (other.dirs);}
Through the local () method in the tool, we can get a collection of files that meet the requirements under the specified directory, and through the walk () method, we can get all the files or directories that meet the requirements under the specified directory, including the files under its subdirectories. This tool is just recorded here for a rainy day.
2. RandomAccessFile
Because the abstract representation of the File class knowledge file does not specify how the information is read from or stored in the file, there are two main ways to read or store information from the file:
Through input and output streams, that is, InputStream, OutputStream
Through RandomAccessFile
The mode of input and output streams will be summarized later, which is also a large part of the Java I pancake O system. This article will talk about RandomAccessFile because it is relatively independent and has little correlation with streams.
RandomAccessFile is a completely separate class that has fundamentally different behavior from the IO type we will summarize later and can move forward and backward within a file. Let's take a look at the main methods:
Void write (int d) writes 1 byte to the file, writing the incoming int value corresponding to the lower 8 bits of the binary
Int read () reads 1 byte and returns it as int. If-1 is returned, the end of the file is reached.
Int read (byte [] data) reads the number of bytes of the total length of the byte array from the file at one time and stores them in the byte array. The int value returned represents the total number of bytes read, and if-1 is returned, no data has been read. Usually the length of the byte array can be specified as 1024010 (about the appearance of 10Kb, the efficiency is better)
Int read (byte [] data, int off, int len) reads up to len bytes from the file at one time and stores them in the data array, starting with the subscript off
Void write (int b) writes 1 byte of content to the file so that the passed int value corresponds to the lower 8 bits of the binary
Write (byte b []) writes the contents of a byte array to the file
Write (byte b [], int off, int len) writes to the file len bytes starting with the subscript off of array b
Seek (long pos) sets the file pointer offset to the specified value, that is, to move to a new location within the file
Long getFilePointer () gets the current location of the file pointer
Void close () closes RandomAccessFile
The above is only part of the method, please refer to the official documentation for more. Let's take another look at a simple demo to learn:
Public class RandomAccessFileDemo {public static void main (String [] args) {File file = new File (". / test.txt"); if (! file.exists ()) {try {file.createNewFile ();} catch (IOException E1) {e1.printStackTrace ();}} RandomAccessFile raf = null;try {raf = new RandomAccessFile (". / test.txt", "rw"); raf.write (1000); raf.seek (0); System.out.println (raf.read ()); raf.seek (0) System.out.println (raf.readInt ());} catch (FileNotFoundException e) {System.out.println ("file not found");} catch (EOFException e) {System.out.println ("reachs end before read enough bytes"); e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} finally {try {raf.close ();} catch (IOException e) {e.printStackTrace ();}
Output result:
232reachs end before read enough bytes
There are two parameters in the constructor of the RandomAccessFile, the first is the file path or File, which represents the file to be operated on by the RandomAccessFile, and the second is the read-write mode. If the file for the operation does not exist, the file will be created directly when the mode is "rw" and an exception will be thrown if it is "r".
This is a simple example, first create a file test.txt, then create a RandomAccessFile associated with the file, specify read-write mode to read-write, call write () write 1000, here only write one byte, jump to the file header, read 1 byte, output 232 (exactly 1000 corresponding to the lower 8 bits of binary), then jump to the file header and call readInt () to read an integer At this point, because there is only 1 byte in the file, an EOFException exception is thrown and RandomAccessFile is closed.
As in the example above, we learned the basic usage of RandomAccessFile. It is important to note that RandomAccessFile reads and writes from the current location based on the file pointer, and the write operation overwrites the content after the insertion point directly rather than inserting it. If we want to implement the insert operation, we need to save the content after the insertion point, then write the content to be inserted, and finally add the saved content, see the following example:
Public class RandomAccessFileDemo {public static void main (String [] args) throws IOException {File file = new File ("f:/test.txt"); file.createNewFile (); / / create a temporary space-time file for buffering and specify that it be deleted when the virtual machine stops File temp = File.createTempFile ("temp", null); temp.deleteOnExit (); RandomAccessFile raf = null Try {/ / first write the following poem to the file and read it out and print raf = new RandomAccessFile (file, "rw") on the console; raf.write ("when is the bright moon, ask the wine in the blue sky" .getBytes ()); raf.seek (0); byte [] b = new byte [60]; raf.read (b, 0,30); System.out.println (new String (b)); / next insert a poem raf.seek (12) in the middle of the poem FileOutputStream fos = new FileOutputStream (temp); FileInputStream fis = new FileInputStream (temp); byte [] buffer = new byte [10]; int num = 0politics while (- 1! = (num = raf.read (buffer) {fos.write (buffer, 0, num);} raf.seek (12); raf.write. .getBytes (); / / add the second half of the buffer to while (- 1! = (num = fis.read (buffer) {raf.write (buffer, 0, num);} raf.seek (0); raf.read (b, 0,60); System.out.println (new String (b)); System.out.println ();} catch (FileNotFoundException e) {e.printStackTrace ();} finally {raf.close ();}
Output the result, insert the poem successfully:
When does the bright moon have, ask the wine when the blue sky bright moon has, but wish the person for a long time, thousands of miles together Juan. Ask Qingtian about the wine. Thank you for reading this article carefully. I hope the article "sample Analysis of File and RandomAccessFile of Java Iripple O" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.