Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of java's document IO

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "java file IO example analysis", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "java document IO example analysis" bar!

File IZP O

The new IO class library has been introduced into the java.nio.* package of JDK 1.4, which is designed to improve speed. In fact, the old IO package has been reimplemented using nio to take full advantage of this speed increase. The increase in speed comes from the structure used that is closer to the way the operating system executes IO: channels and buffers. We can think of it as a coal mine, the channel is a mineral deposit containing the coal seam (data), and the buffer is the truck delivered to the mine. The truck came home full of coal, and we got coal from the truck. That is, we don't interact directly with the channel, we just interact with the buffer and dispatch the buffer to the channel. Either get data from the buffer or send data to the buffer.

The only buffer that interacts directly with the channel is the buffer where ByteBuffer-- can store raw bytes. Java.nio.ByteBuffer is a fairly basic class: a ByteBuffer object is created by telling how much storage space is allocated, and there is also a method selection set for outputting and reading data in raw byte form or basic data types. However, there is no way to output or read objects, even string objects. This processing is low-level, but it is just right, because it is a more efficient mapping in most operating systems.

Three classes in the old IO class library have been modified to generate FileChannel. The three modified classes are FileInputStream, FileOutputStream, and RandomAccessFile for both reading and writing. These are byte operation flows that are consistent with the underlying nio. Character pattern classes such as Reader and Writer cannot be used to generate channels; however, the java.nio.channels.Channels class provides applicable methods for generating Reader and Writer in channels.

/ / demonstrate the above three types of streams, which are used to generate writable, readable, and readable channels package com.wise.tiger; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class GetChannel {private static final int BUFF_SIZE = 1024 Public static void main (String [] args) throws IOException {/ / write file FileChannel fc = new FileOutputStream ("data.txt") .getChannel () / * * using the warp () method to wrap an existing byte array into ByteBuffer can also be populated directly with the put method * / fc.write (ByteBuffer.wrap ("I'm Peppa Pig." .getBytes ()); fc.close () / / add content fc = new RandomAccessFile ("data.txt", "rw"). GetChannel (); fc.position (fc.size ()); / / move to the end of the file fc.write (ByteBuffer.wrap ("This is my little brother, George" .getBytes ()); fc.close () / / read the file fc = new FileInputStream ("data.txt") .getChannel () / * * assign ByteBuffer. For read-only access, you must explicitly use the static allocate () method to allocate ByteBuffer * the goal of nio is to move large amounts of data quickly, so the size of the ByteBuffer is particularly important (the best size must be found through the actual running program) * / ByteBuffer buff = ByteBuffer.allocate (BUFF_SIZE) / * * once you call read () to tell FileChannel to store bytes to ByteBuffer, you must call flip () on the buffer and get it ready for someone else to read the bytes. * if you plan to use the buffer to perform further read () operations, you must also use clear () to prepare for each read (), as shown in the copy file * / fc.read (buff); buff.flip (); while (buff.hasRemaining ()) {System.out.print ((char) buff.get ()) } fc.close ();}}

Any stream class shown here, getChannel () will produce a FileChanel. A channel is a fairly basic thing: it can be passed ByteBuffer for reading and writing, and certain areas of the file can be locked for exclusive access.

Public class ChannelCopy {private static final int CAPACITY = 1024; public static void main (String [] args) throws IOException {if (args.length! = 2) System.exit (1); FileChannel in = new FileInputStream (args [0]). GetChannel (), out = new FileOutputStream (args [1]). GetChannel (); ByteBuffer buff = java.nio.ByteBuffer.allocate (CAPACITY) While (in.read (buff)! =-1) {buff.flip (); out.write (buff); buff.clear ();} out.close (); in.close ();}}

However, this program is not an ideal way to handle such operations, and the special methods transferTo () and transferFrom () allow us to connect one channel directly to another.

Public class ChannelCopy {private static final int CAPACITY = 1024; public static void main (String [] args) throws IOException {if (args.length! = 2) System.exit (1); FileChannel in = new FileInputStream (args [0]). GetChannel (), out = new FileOutputStream (args [1]). GetChannel (); in.transferTo (0jin.size (), out) / / or out.transferFrom (in,0,in.size); out.close (); in.close ();}} convert data

In GetChannel.java, you must read only one byte of data at a time, and then cast each byte type to a char type. Java.nio.CharBuffer has a toString method that returns a string containing all the characters in the buffer. ByteBuffer can be thought of as a CharBuffer with an asCharBuffer () method.

Public class BufferToText {private static final int CAPACITY = 1024; public static void main (String [] args) {try {var fc = new FileOutputStream ("data.txt"). GetChannel (); fc.write ("come, I am a banana." .getBytes (); fc.close (); fc = new FileInputStream ("data.txt"). GetChannel (); var buff = ByteBuffer.allocate (CAPACITY); fc.read (buff); buff.flip (); System.out.println (buff.asCharBuffer ()); buff.rewind () / return to the beginning of the data var encoding = System.getProperty ("file.encoding"); / / get the default character set System.out.println ("use" + encoding + "decoding result:" + Charset.forName (encoding) .decode (buff)); fc = new FileOutputStream ("data.txt"). GetChannel () Fc.write (ByteBuffer.wrap ("come, I am a durian" .getBytes ("UTF-8")); fc.close (); fc = new FileInputStream ("data.txt"). GetChannel (); buff.clear (); fc.read (buff); buff.flip () System.out.println (buff.asCharBuffer ()); fc = new FileOutputStream ("data.txt"). GetChannel (); buff = ByteBuffer.allocate (24); buff.asCharBuffer (). Put ("beauty like flowers"); fc.write (buff); fc.close () Fc = new FileInputStream ("data.txt"). GetChannel (); buff.clear (); fc.read (buff); buff.flip (); System.out.println (buff.asCharBuffer ());} catch (IOException e) {e.printStackTrace ();}

Buffers hold ordinary bytes, and in order to convert them into characters, we either encode them when we input them or decode them when they are output from the buffer (you can use the java.nio.charset.Charset class to achieve these functions).

Get the basic type

Although ByteBuffer can only save byte type data, it can generate a variety of methods for primitive type values from the bytes it contains

CharBuffer = > asCharBuffer ()

ShorBuffer = > asShortBuffer ()

IntBuffer = > asIntBuffer ()

LongBuffer = > asLongBuffer ()

FloatBuffer = > asFloatBuffer ()

DoubleBuffer = > asDoubleBuffer ()

These Buffer cover the basic data types you can send over IO: byte, short, int, long, float, double and char.

Note: type conversion is required when using the put () method of shortBuffer.

View buffer

The View buffer (view buffer) allows us to view its underlying ByteBuffer through a window of a particular basic data type. The ByteBuffer is still the place where the data is actually stored, "supporting" the previous view, so any changes to the view will be mapped to changes to the data in ByteBuffer.

Once the underlying ByteBuffer is filled with integers or other basic types through the view buffer, it can be written directly to the channel. It's just as easy to read from a channel, and then you can use a view buffer to convert any data to a particular basic type.

Manipulate data with buffers

The following figure illustrates the relationship between nio classes so that we can understand how to move and transform data. If you want to write a byte array to a file, you should wrap the byte array with the ByteBuffer.wrap () method, then open a channel on the FileOutputStream with the getChannel () method, and then write the data from ByteBuffer to FileChannel.

Note: BytBuffer is the only way to move data in and out of the channel, and you can only create a separate primitive type buffer, or use the as method to get it from ByteBuffer. That is, you cannot convert a basic type of buffer to ByteBuffer. However, we can move basic type data in and out of Bytebuffer via the view buffer, so it's not a real limitation.

Buffer details

Buffer consists of data and four indexes that can access and manipulate that data efficiently, mark (tag), position (location), limit (limit), and capacity (capacity). Here are the methods for setting and resetting indexes and querying their values.

Capacity () returns buffer capacity clear () clears the cache, sets position to 0 and sets limit to capacity. You can call this method to override the buffer flip () and set limit to the position,position setting of 0. 0. This method is used to prepare to read written data from the buffer limit () returns the value of limit limit (int lim) returns the value of limit mark () sets mark to positionposition () returns position value position (int pos) returns position value remaining () returns (limit-position) hasRemaining () whether there is an element between position and limit

The method of inserting and extracting data in the buffer updates these indexes to reflect the changes that have occurred.

Memory mapping file

Memory-mapped files allow you to create and modify files that are too large to fit into memory. You can assume that the entire file is in memory and that it can be accessed entirely as a very large array.

Public class LargeMappedFiles {static int length = 0x8FFFFF; / 128 MB public static void main (String [] args) throws Exception {MappedByteBuffer out = new RandomAccessFile ("test.dat", "rw") .getChannel () .map (FileChannel.MapMode.READ_WRITE, 0, length); for (int I = 0; I < length) ITunes +) {out.put ((byte)'x');} print ("Finished writing"); for (int I = length / 2; I < length / 2 + 6; iTunes +) {printnb ((char) out.get (I));}

Use map () to generate MappedByteBuffer, a special type of direct buffer. Note: the initial location of the mapping file and the length of the mapping area must be specified, meaning that a smaller portion of a large file can be mapped.

MappedByteBuffer is inherited from ByteBuffer, so it has all the methods of ByteBuffer.

The file created by the previous program is 128MB, which may be more space than the operating system allows to load memory at a time. But it seems that we can access the whole file at once. Because only some of the files are in memory, others are swapped out. In this way, large files (up to 2GB) can also be easily modified. Note that the file mapping tool of the underlying operating system is used to maximize performance.

All output of the mapping file must use RandomAccessFile.

File locking

JDK 1.4 introduces a file locking mechanism that allows synchronous access to a file that is a shared resource. File locks are visible to other operating system processes because Java's file locks map directly to the locking tools of the local operating system.

Public class FileLocking {public static void main (String [] args) throws Exception {FileOutputStream fos= new FileOutputStream ("file.txt"); FileLock fl = fos.getChannel (). TryLock (); if (fl! = null) {System.out.println ("Locked File"); TimeUnit.MILLISECONDS.sleep (100); fl.release (); System.out.println ("Released Lock");} fos.close () }} / * Locked File Released Lock * /

By calling tryLock () or lock () on FileChannel, you can get the FileLock of the entire file. SocketChannel, DatagramChannel, and ServerSocketChannel do not need to be locked because they inherit from a single-process entity and typically do not share socket between the two processes. TryLock (), which is non-blocking, tries to acquire the lock and returns directly from the method call if it cannot be obtained (when some other process already holds the same lock and does not share it). Lock () is blocking, blocking the process until the lock is available, or the thread calling lock () is interrupted, or the channel calling lock () is closed. Use FileLock.release () to release the lock.

You can also lock parts of a file using the following methods:

TryLock (long position, long size, boolean shared)

Or

Lock (long position, long size, boolean shared)

Where the locking area is determined by the size-position, and the third parameter specifies whether the lock is shared.

Although the no-parameter locking method will change according to the file size, the lock with fixed size does not change with the file size. If you acquire a lock on an area (from position to position+size), when the file grows beyond the position+size, then parts outside the position+size will not be locked. The parameterless locking method locks the entire file, even when the file becomes larger.

Support for exclusive or shared locks must be provided by the underlying operating system. If the operating system does not support shared locks and does not create locks for every request, it uses exclusive locks. The type of lock can be queried through FileLock.isShared ().

Lock parts of the mapping file

File mapping is usually applied to very large files. We may need to partially lock this large file so that other processes can modify the unlocked parts of the file. For example, a database is like this, so multiple users can access it at the same time.

Public class LockingMappedFIles {static final int LENGTH = 0x8FFFFFFFFFF) throws IOException 128m static FileChannel fc; public static void main (String [] args) throws IOException {fc = new RandomAccessFile ("test.dat", "rw"). GetChannel (); MappedByteBuffer out = fc.map (FileChannel.MapMode.READ_WRITE, 0, LENGTH); for (int I = 0; I < LENGTH; I +) out.put ((byte)'x') New LockAndModify (out, 0,0 + LENGTH / 3); new LockAndModify (out, LENGTH / 2, LENGTH / 2 + LENGTH / 4);} private static class LockAndModify extends Thread {private ByteBuffer buff; private int start,end; public LockAndModify (ByteBuffer buff, int start, int end) {this.start = start; this.end = end Buff.limit (end); buff.position (start); this.buff = buff.slice ();} @ Override public void run () {try {FileLock lock = fc.lock (start,end,false); System.out.println ("Locked:" + start + "to" + end) While (buff.position () < buff.limit ()-1) buff.put ((byte) (buff.get () + 1)); lock.release (); System.out.println ("Released:" + start + "to" + end) } catch (IOException e) {e.printStackTrace ();}}

The thread class LockAndModify creates a buffer and slice () for modification, and then in run, obtains the lock on the file channel (you can't get the lock on the buffer, only on the channel). Lock () is similar to a thread lock that acquires an object-is now in a critical area, that is, has exclusive access to that part of the file.

If there is a java virtual machine, it automatically releases the lock or closes the locked channel. However, as in the program, you can explicitly call release () for the FileLock object to release.

Thank you for your reading, the above is the content of "java document IO example Analysis", after the study of this article, I believe you have a deeper understanding of the java document IO example analysis of this problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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: 256

*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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report