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

How to quickly understand IO streams in Java

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to quickly understand the IO stream in Java". In the daily operation, I believe many people have doubts about how to quickly understand the IO stream in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to quickly understand the IO stream in Java". Next, please follow the editor to study!

one。 File class

1. A brief introduction

An object of the File class can represent both the name of a specific file and the name of a set of files in a directory.

File can create, delete, and rename files and directories, but File cannot access the contents of the files themselves. If you need to access the contents of the file itself, you need to use the input / output stream.

To represent a real file or directory in a Java program, you must have a File object, but a File object in a Java program may not have a real file or directory.

Objects of subsequent File classes are often passed as parameters to the stream's constructor, indicating the "end point" of reading or writing.

two。 Basic usage

In a file system, each file is stored in a directory. The absolute file name (absolute file name) consists of the file name and its full path and drive letters. The relative file name is relative to the current working directory. For example, c:\ book\ Welcome.java is the absolute file name of the file Welcome.java on the Windows operating system. Welcome.java is a relative file name.

Windows and DOS systems use "\" by default to indicate that UNIX and URL use "/" to indicate that Java programs support cross-platform running, so path delimiters should be used with caution. To solve this problem, the File class provides a constant: public static final String separator. Provide delimiters dynamically, depending on the operating system. File file = new File ("D:" + File.separator + "JavaSE" + File.separator + "JavaProject")

2.1 Construction method

Public File (String pathname) creates File objects with pathname as the path, which can be absolute or relative

Public File (String parent,String child) creates File objects with parent as the parent path and child as the subpath.

Public File (File parent,String child) creates a File object based on a parent File object and child file path

/ / Constructor 1: public File (String pathname) File file1 = new File ("hello.txt"); / / relative path File file2 = new File ("D:\ JavaSE\\ JavaProject\\ WorkSpace\\ ioDemo\\ hi.txt"); / / absolute path System.out.println (file1); System.out.println (file2) / / Constructor 2: public File (String parent,String child) File file3 = new File ("D:\\ JavaSE", "JavaProject"); System.out.println (file3); / / Constructor 3: public File (File parent,String child) File file4 = new File (file3, "he.txt"); System.out.println (file4)

Output result:

2.2 Common methods

2.2.1 acquisition function of File class

Public String getAbsolutePath (): get the absolute path

Public String getPath (): get the path

Public String getName (): get the name

Public String getParent (): gets the path to the upper file directory. If none, null is returned. If the file object is a relative path, null is returned.

Public long length (): gets the file length (that is, the number of bytes). Cannot get the length of the directory.

Public long lastModified (): gets the last modification time, millisecond value, and returns 0 if the file does not really exist on the hard disk.

Public String [] list (): gets an array of names of all files or file directories under the specified directory

Public File [] listFiles (): gets the File array of all files or file directories under the specified directory

@ Test public void test4 () {File file1 = new File ("hello.txt"); / / does not exist, just an object File file2 = new File ("D:\\ io\\ hi.txt"); / / System.out.println (file1.getAbsolutePath ()) exists on the hard disk; System.out.println (file1.getPath ()); System.out.println (file1.getName ()) System.out.println (file1.getParent ()); System.out.println (file1.length ()); System.out.println (file1.lastModified ()); System.out.println ("* *"); System.out.println (file2.getAbsolutePath ()) System.out.println (file2.getPath ()); System.out.println (file2.getName ()); System.out.println (file2.getParent ()); System.out.println (file2.length ()); System.out.println (file2.lastModified ());} copy code

Output result:

2.2.2 judgment function of File class

Public boolean isDirectory (): determines whether it is a file directory

Public boolean isFile (): determines whether it is a file or not

Public boolean exists (): determine whether it exists

Public boolean canRead (): judge whether it is readable or not

Public boolean canWrite (): judge whether it is writable or not

Public boolean isHidden (): determine whether to hide or not

@ Test public void test5 () {File file1 = new File ("hello.txt"); / / there is real File file2 = new File ("hello1.txt") on the hard disk; / / System.out.println (file1.isDirectory ()); System.out.println (file1.isFile ()); System.out.println (file1.exists ()); System.out.println (file1.canRead ()) System.out.println (file1.canWrite ()); System.out.println (file1.isHidden ()); System.out.println ("* *"); System.out.println (file2.isDirectory ()); System.out.println (file2.isFile ()); System.out.println (file2.exists ()) System.out.println (file2.canRead ()); System.out.println (file2.canWrite ()); System.out.println (file2.isHidden ()); System.out.println ("* *"); File file3 = new File ("d:\\ io") / / Real File file4 = new File ("d:\\ io1"); / / No System.out.println (file3.isDirectory ()); System.out.println (file3.isFile ()); System.out.println (file3.exists ()); System.out.println (file3.canRead ()); System.out.println (file3.canWrite ()); System.out.println (file3.isHidden ()) System.out.println ("* *"); System.out.println (file4.isDirectory ()); System.out.println (file4.isFile ()); System.out.println (file4.exists ()); System.out.println (file4.canRead ()); System.out.println (file4.canWrite ()) System.out.println (file4.isHidden ());} copy the code

Output result:

2.2.3 other functions of the File class

Public boolean createNewFile (): create a file. If the file exists, it will not be created and false will be returned. Specifies that the directory of the file should exist. Public boolean delete (): delete files or folders, delete notes: deletes in Java do not go to the Recycle Bin. For the folder to be deleted successfully, there must be no subdirectories or files in the last file directory

@ Test public void test6 () throws IOException {File file1 = newFile ("hello.txt"); / / if (! file1.exists ()) {/ / the creation of the file boolean newFile = file1.createNewFile (); System.out.println ("file created successfully");} else {boolean delete = file1.delete () System.out.println ("original file deleted successfully");}} copy code

Public boolean mkdir (): create a file directory. If this file directory exists, it will not be created. If the upper directory of this file directory does not exist, it will not be created.

Public boolean mkdirs (): create a file directory. If the upper file directory does not exist, create it at the same time

@ Test public void test7 () {/ / the creation of the file directory File file1 = new File ("d:\ io\\ io1\\ io2"); / / only the io directory exists at this time boolean mkdir = file1.mkdir (); if (mkdir) {System.out.println ("created successfully 1");} File file2 = new File ("d:\ io\\ io1\\ io2") / / only the io directory has boolean mkdirs = file2.mkdirs (); if (mkdirs) {System.out.println ("created successfully 2");}} copy code

Output result:

Public boolean renameTo (File dest): rename the file to the specified file path, such as file1.renameTo (file2) as an example: to ensure that true is returned, file1 needs to exist on the hard disk, and file2 cannot exist on the hard disk.

@ Test public void test9 () {File file1 = new File ("hello.txt"); / / exists on the hard disk with the content "hello world!" File file2 = new File ("D:\\ io\\ hi.txt"); / / boolean renameTo = file1.renameTo (file2); System.out.println (renameTo);} code does not exist in hi.txt

Output result: generated the original non-existent hi.txt file, the content is hello world! The hello.txt location has moved.

The default relative path of File in main () method in idea is different from that of File in Junit Test method.

Public class FileMainTest {public static void main (String [] args) {File file = new File ("hello.txt"); System.out.println ("main" + file.getAbsoluteFile ()); / / output result: mainD:\ JavaSE\ JavaProject\ WorkSpace\ hello.txt} @ Test public void test1 () {File file = new File ("hello.txt"); System.out.println ("test" + file.getAbsoluteFile ()) / / output result: testD:\ JavaSE\ JavaProject\ WorkSpace\ ioDemo\ hello.txt}} copy the code

two。 IO flow

1. A brief introduction

Java provides a number of classes that implement file input / output. These classes can be divided into two categories: the literal text O class and the binary binary O class.

Input object (input stream) reads external data (data from disk, optical disc and other storage devices) to the program (memory). In the process of operation, we use the program (memory) point of view.

Output object (output stream) outputs program (memory) data to disk, optical disc and other storage devices.

1.1 Classification of streams

According to the operating data units, it is divided into: byte stream (8 bit), character stream (16 bit)

According to the flow direction of the data stream, it can be divided into input stream and output stream.

According to the role of the flow is divided into: node flow, processing flow

Java's IO stream involves more than 40 classes, which are actually very regular, all derived from the following four abstract base classes. Subclass names derived from these four classes are all suffixed with their parent class names.

two。 Node stream (file stream)

When defining a file path, note that you can use "/" or "\".

When writing a file, if you use the constructor FileOutputStream (file), a file with the same name in the directory will be overwritten.

If you use the constructor FileOutputStream (file,true), the file with the same name in the directory will not be overwritten and the content will be appended to the end of the file content.

When reading a file, you must ensure that the file already exists, otherwise an exception is reported.

Byte stream operation bytes, such as .mp3, .avi, .rmvb, mp4,.jpg,.doc,.ppt

Character stream manipulates characters, only plain text files can be manipulated. The most common text files: source code for .txt, .java, .c, .cpp and other languages. Pay special attention to .doc, excel,ppt these are not text files.

2.1 FileReader/FileWriter (character stream)

2.1.1 Common methods for FileReader

Int read (): reads a single character. Characters read as integers ranging from 0 to 65535 (0x00-0xffff) (2-byte Unicode code), or-1 if the end of the stream has been reached

Int read (char [] cbuf): reads characters into an array. Returns-1 if the end of the stream has been reached. Otherwise, the number of characters read this time is returned.

Int read (char [] cbuf,int off,int len): reads characters into a part of an array. Save it to the array cbuf, start at off, and read up to len characters. Returns-1 if the end of the stream has been reached. Otherwise, the number of characters read this time is returned.

Public void close () throws IOException: closes this input stream and releases all system resources associated with the stream.

2.1.2 basic usage

Almost all methods in the Imax O class throw an exception; java.io.IOException. Therefore, you must declare in the method that the java.io.IOException exception will be thrown, or put the code in the try-catch block.

/ / read the contents of the hello.txt file under module into the program and output to the console @ Test public void test1 () throws IOException {FileReader fr = null; try {/ / 1.File class instantiation File file = new File ("hello.txt"); / / instantiation fr = new FileReader (file) of the 2.FileReader stream / / 3. Read in using read (char [] cbuf) char [] cbuf = new char [5]; int len; while ((len = fr.read (cbuf))! =-1) {/ / method 1 / / for (int I = 0; I)

< len; i++) {//不能用cbuf.length // System.out.print(cbuf[i]); // } //方法二 String s = new String(cbuf, 0, len); System.out.print(s); } } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { //4.资源的关闭 fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } 复制代码 输出结果: 2.1.1 FileWriter常用方法 void write(int c):写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。 即写入0 到 65535 之间的Unicode码。 void write(char[] cbuf):写入字符数组。 void write(char[] cbuf,int off,int len):写入字符数组的某一部分。从off开始,写入len个字符写入字符串。 void write(String str,int off,int len):写入字符串的某一部分。 void flush():刷新该流的缓冲,则立即将它们写入预期目标。 public void close()throws IOException :关闭此输出流并释放与该流关联的所有系统资源 2.1.2 基本用法 鸿蒙官方战略合作共建--HarmonyOS技术社区 输出操作,对应的File可以不存在的。并不会报异常 File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。 File对应的硬盘中的文件如果存在: ① 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖 ② 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容 //从内存中写出数据到硬盘的文件里 @Test public void test2() { FileWriter fw = null; try { //1.创建File类的对象,指明写出的文件 File file = new File("hello1.txt"); //2.提供FileWrite的对象,用于数据的写出 fw = new FileWriter(file); //3.写出的操作 fw.write("I have a dream!\n"); fw.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { //4.关闭资源 try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } 复制代码 实现文本之间的复制 @Test public void test3() { FileReader fr = null; FileWriter fw = null; try { //1.创建File类的对象,指明读入与写出的文件 File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //2.創建输入流与输出流的对象 fr = new FileReader(srcFile); fw = new FileWriter(destFile); //3.数据的读入与写出的操作 char[] cbuf = new char[5]; int len; while ((len = fr.read(cbuf)) != -1) { fw.write(cbuf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭流资源 try { if (fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fr != null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } } 制代码 2.2 FileInputStream/FileOutputStream(字节流) 2.2.1 FileInputStream常用方法 int read():从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。 int read(byte[] b):从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数。 int read(byte[] b, int off,int len):将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1。 public void close() throws IOException:关闭此输入流并释放与该流关联的所有系统资源。 2.2.2 FileOutputStream常用方法 void write(int b):将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 即写入0~255范围的。 void write(byte[] b):将 b.length 个字节从指定的 byte 数组写入此输出流。write(b) 的常规协定是:应该与调用 write(b, 0, b.length) 的效果完全相同。 void write(byte[] b,int off,int len):将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。 public void flush()throws IOException:刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立即写入它们预期的目标。 public void close() throws IOException:关闭此输出流并释放与该流关联的所有系统资源。 2.2.3 基本用法 @Test public void test1() { FileInputStream fis = null; FileOutputStream fos = null; try { //1.造文件对象 File srcFile = new File("photo1.jpg"); File destFile = new File("photo2.jpg"); //2.造流 fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //3.读数据 byte[] buffer = new byte[5]; int len; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭资源 try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } } 制代码 复制成功 3.缓冲流 为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流 flush()方法的使用:手动将buffer中内容写入文件 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出 3.1 BufferedInputStream/BufferedOutputStream @Test public void test1() { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件对象 File srcFile = new File("D:\\QQmusic\\MV\\1988.mp4"); File descFile = new File("D:\\QQmusic\\MV\\copy1988.mp4"); //2.1造节点流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(descFile); //2.2造缓冲流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.数据读入与写出操作 byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭资源 try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } //说明:先关闭外层的流,再关闭内层的流 // 关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略. // fos.close(); // fis.close(); } } 复制代码 结果:成功复制 3.2 BufferedReader/BufferedWriter @Test public void test2() throws IOException { BufferedReader br = null; BufferedWriter bw = null; try { //创建文件和相应的流 // BufferedReader br = new BufferedReader(new FileReader(new File("hello.txt"))); br = new BufferedReader(new FileReader("hello.txt")); bw = new BufferedWriter(new FileWriter("hello3.txt")); //读写操作 //方式一 char[] cbuf = new char[1024]; int len; while ((len = br.read(cbuf)) != -1) { bw.write(cbuf, 0, len); } // //方式二 // String data; // while ((data = br.readLine())!= null){//一次读取字符文本文件的一行字符 // bw.write(data);//data中不包含换行符, 一次写入一行字符串 // bw.newLine(); // //bw.write(data + "\n"); // } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) bw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } } } 复制代码 4.转换流 4.1 InputStreamReader/OutputStreamWriter 转换流提供了在字节流和字符流之间的转换 Java API提供了两个转换流: InputStreamReader:将InputStream转换为Reader OutputStreamWriter:将Writer转换为OutputStream 字节流中的数据都是字符时,转成字符流操作更高效。 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。 编码:字符串——>

Byte array decoding: byte array-- > string

/ * combine InputStreamReader with OutputStreamWriter * / @ Test public void test1 () {InputStreamReader isr = null;// default IDE character set OutputStreamWriter osw = null; try {/ / 1. File object File file1 = new File ("hello.txt"); File file2 = new File ("hello_gbk.txt"); / / 2. FileInputStream fis = new FileInputStream (file1); FileOutputStream fos = new FileOutputStream (file2); / / InputStreamReader isr = new InputStreamReader (fis, "UTF-8"); isr = new InputStreamReader (fis); osw = new OutputStreamWriter (fos, "gbk"); / / OutputStreamWriter osw = new OutputStreamWriter (fos, "gbk"); / / 3. Data reading and writing process char [] cbuf = new char [20]; int len; while ((len = isr.read (cbuf))! =-1) {osw.write (cbuf, 0, len);}} catch (IOException e) {e.printStackTrace ();} finally {/ / 4. Close the resource try {if (isr! = null) isr.close ();} catch (IOException e) {e.printStackTrace ();} try {if (osw! = null) osw.close () } catch (IOException e) {e.printStackTrace ();} copy the code

5. Object stream

5.2 serialization of objects

ObjectlnputStream class and ObjectOutputStream class can realize not only the input and output of basic data types and strings, but also the input and output of objects.

Serialization: a mechanism for saving basic type data or objects with ObjectOutputStream classes

Deserialization: the mechanism for reading basic type data or objects with the ObjectInputStream class

ObjectOutputStream and ObjectInputStream cannot serialize member variables modified by static and transient

The object serialization mechanism allows Java objects in memory to be converted into platform-independent binary streams, thus allowing the binary stream to be persisted on disk or transmitted to another network node over the network. / / when other programs acquire this binary stream, it can revert to the original Java object

The advantage of serialization is that any object that implements the Serializable interface can be converted into byte data so that it can be restored when saved and transferred.

Serialization is a mechanism that must be implemented for both parameters and return values of RMI (Remote Method Invoke-remote method invocation) procedures, and RMI is the foundation of JavaEE. So serialization mechanism is the foundation of JavaEE platform.

If you need an object to support a serialization mechanism, you must make the class to which the object belongs and its properties serializable, and in order for a class to be serializable, the class must implement one of the following two interfaces. Otherwise, a NotSerializableException exception Serializable Externalizable will be thrown

All classes that implement the Serializable interface have a static variable that represents the serialized version identifier: private static final long serialVersionUID; serialVersionUID is used to indicate compatibility between different versions of the class. In short, the purpose is to version control with serialized objects, which is about whether each version is compatible when deserializing. If the class does not show the definition of this static constant, its value is automatically generated by the Java runtime environment based on the internal details of the class. If the instance variable of the class is modified, the serialVersionUID may change. Therefore, it is recommended that = explicitly declare =

To put it simply, Java's serialization mechanism verifies version consistency by determining the serialVersionUID of the class at run time. When deserializing, JVM compares the serialVersionUID in the incoming byte stream with the serialVersionUID of the corresponding local entity class. If the same is considered to be consistent, it can be deserialized, otherwise an exception of inconsistent serialization version will occur. (InvalidCastException)

To talk about your understanding of the java.io.Serializable interface, we know that it is used for serialization, it is an empty method interface, is there anything else?

Objects that implement the Serializable interface can be converted into a series of bytes and can be fully restored later. This process can also be carried out through the network. This means that the serialization mechanism can automatically compensate for differences between operating systems. In other words, you can create an object on a Windows machine, serialize it, send it to a Unix machine over the network, and then "reassemble" there exactly. You don't have to care about how the data is represented on different machines, or the order of bytes or any other details. Because most of the classes as parameters, such as String, Integer and so on, implement the interface of java.io.Serializable, we can also make use of the property of polymorphism as parameters to make the interface more flexible.

5.1 ObjectInputStream/ObjectOutputStream

If a class implements the Serializable interface, the object of the class is serializable:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Create an ObjectOutputStream

Call the writeObject (object) method of the ObjectOutputStream object to output serializable objects

Pay attention to write out once, and operate flush () once.

Deserialization

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Create an ObjectInputStream

Call the readObject () method to read the objects in the stream

Emphasis: if the property of a class is not a base data type or String type, but another reference type, then the reference type must be serializable, otherwise the class that owns the Field of that type cannot be serialized

Package objectTest; import org.junit.Test; import java.io.*; / * * @ author mazouri * @ create 2020-04-21 20:08 * / public class ObjectInOutputStream {/ * serialization process: saving java objects in memory to disk or transferring them over the network * using ObjectOutputStream * / @ Test public void test1 () {ObjectOutputStream oos = null Try {oos = new ObjectOutputStream (new FileOutputStream ("object.dat")); oos.writeObject (new Person ("Zhang San", 18)); / / refresh operation oos.flush (); oos.writeObject ("Li Si", 23, 1001, new Account (5000)); oos.flush () } catch (IOException e) {e.printStackTrace ();} finally {try {if (oos! = null) oos.close ();} catch (IOException e) {e.printStackTrace () } / * * deserialization: restore an object in a disk file to a java object in memory * use ObjectInputStream to implement * / @ Test public void test2 () {ObjectInputStream ois = null; try {ois = new ObjectInputStream (new FileInputStream ("object.dat")) Person p = (Person) ois.readObject (); Person p1 = (Person) ois.readObject (); System.out.println (p + "\ n" + p1);} catch (IOException | ClassNotFoundException e) {e.printStackTrace () } finally {try {if (ois! = null) ois.close ();} catch (IOException e) {e.printStackTrace ();} copy the code

Output result:

6. Random access file stream

So far, all streams used have been read-only (read.only) or write.only-only. These processes are sequential flows. Files that are opened using sequential streams are called sequential access files. The contents of the sequential access file cannot be updated. However, files often need to be modified. Java provides the RandomAccessFile class, which allows you to read and write anywhere in the file. Files opened with the RandomAccessFile class are called random access files.

The RandomAccessFile declaration is under the java.io package, but inherits directly from the java.lang.Object class. And it implements DataInput and DataOutput interfaces, which means that this class can both read and write.

RandomAccessFile supports "random access". Programs can skip to any place of the file to read and write files. Only part of the contents of the file can be accessed and appended to existing files.

The RandomAccessFile object contains a record pointer that indicates the location of the current read and write. RandomAccessFile class objects can freely move the record pointer: long getFilePointer (): get the current location of the file record pointer void seek (long pos): position the file record pointer to the pos location

6.1 RandomAccessFile

Constructor

Public RandomAccessFile (File file, String mode)

Public RandomAccessFile (String name, String mode) to create an instance of the RandomAccessFile class needs to specify a mode parameter, which specifies the access mode of RandomAccessFile: r: open read-only rw: open for reading and writing rwd: open for reading and writing; synchronizing file content updates rws: open for reading and writing; synchronizing file contents and metadata updates

If the mode is read-only r. Instead of creating a file, it reads an existing file, and an exception occurs if the read file does not exist. If the mode is rw read and write. If the file does not exist, it will be created, and if it does, it will not be created.

@ Test public void test1 () {RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try {/ / 1. Raf1 = new RandomAccessFile (new File ("love and friendship .jpg"), "r"); raf2 = new RandomAccessFile (new File ("1.jpg"), "rw") / 2. Byte [] buffer = new byte [1024]; int len; while ((len = raf1.read (buffer))! =-1) {raf2.write (buffer,0,len);}} catch (IOException e) {e.printStackTrace () } finally {/ / 3. If (raf1! = null) {try {raf1.close ();} catch (IOException e) {e.printStackTrace () }} if (raf2! = null) {try {raf2.close ();} catch (IOException e) {e.printStackTrace () } @ Test public void test2 () throws IOException {RandomAccessFile raf1 = new RandomAccessFile ("hello.txt", "rw"); raf1.seek (3); / / adjust the pointer to the position marked 3 raf1.write ("xyz" .getBytes ()); / / raf1.close () } / * use RandomAccessFile to achieve data insertion * / @ Test public void test3 () throws IOException {RandomAccessFile raf1 = new RandomAccessFile ("hello.txt", "rw"); raf1.seek (3) / / set the pointer to the position marked at corner 3 / / save all data after pointer 3 to StringBuilder StringBuilder builder = new StringBuilder ((int) new File ("hello.txt"). Length ()); byte [] buffer = new byte [20]; int len; while ((len = raf1.read (buffer))! =-1) {builder.append (new String (buffer,0,len) } / / recall the pointer and write "xyz" raf1.seek (3); raf1.write ("xyz" .getBytes ()); / / write the data in StringBuilder to the file raf1.write (builder.toString (). GetBytes ()); raf1.close () }} at this point, the study on "how to quickly understand the IO flow in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

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

12
Report