Java file Operations

Source: Internet
Author: User

File operation--filefile represents directory information
  • Listfiles method
  • The Listfiles method of file returns an abstract path to the an array group that represents the file in the directory represented by this abstract path name. Its method definition:

    listFiles()
  • return value : Abstract path An array group, which represents the files and directories in the directory represented by this abstract path name. If the directory is empty, then the array will also be empty. Returns null if the abstract path name does not represent a directory, or an I/O error occurs.

  • FileFilter interface
  • With the Listfiles method we can get all the subkeys under a directory, but sometimes we don't want to get all the subkeys, we can use the overloaded method of file when we want to get some children that meet our actual needs:

    file[] listfiles  (filefilter filter)  

    We see here that the overloaded method requires that we pass in a parameter whose type is FileFilter. What is FileFilter? FileFilter is a filter used for abstract pathname , which is to define a regular rule, so in combination with the Listfiles method, we can return the subkeys that satisfy this filter rule, and others ignore them.

  • FileFilter is an interface, so when we need to define some sort of filtering rule, we can define a class to implement this interface, and an instance of this interface can be passed to the listfiles (filefilter) method of the File class.

    For example:

    File[] list = dir.listFiles(new FileFilter() {      @Override      publicbooleanaccept(File pathname) {          return pathname.getName().startsWith(".");      }});

    The parameter of the method FileFilter the Accept method of the instance and is filtered, and the Listfiles method retains and returns the subkeys that all accept methods return true. In this example, we'll take the name of the Dir neutron term "." The beginning of the return.

File Operations--randomaccessfile creating objects

Brief introduction

Java provides an operation that allows random access to a file, and access includes read and write operations. The class is named Randomaccessfile. The read and write of this class is a pointer-based operation.

Read-only mode

Randomaccessfile has two modes for random access to a file, read-only (read file data only), and read-write mode (read and write to file data).
Read-only mode:

  RandomAccessFile(File file,String mode)      RandomAccessFile(String filename,String mode)

When creating a randomaccessfile, the constructor method it provides requires us to pass in the access pattern: the first parameter of the constructor method is the file that needs to be accessed, and the second parameter is the access pattern:

R ": The string" R "indicates that access to the file is read-only.

Read/write mode
Create a file-access-based read-write mode randomaccessfile we only need to pass in "RW" in the second parameter.

new RandomAccessFile(file,”rw”);

Then the access to the file using Randomaccessfile is readable and writable.

Byte data read and write operations
    • Write (int D) method

    • java void write(int d)

Randomaccessfile provides a way to write bytes to a file:
The method writes a byte based on the current pointer's position, and writes out the "low 8 bits" of the parameter int.

    • Read () method

    • java int read()

Randomaccessfile provides a way to read bytes from a file:
The method reads a byte (8-bit) padding from the current pointer position of Randomaccessfile to the low eight bits of int, a height of 24 bits is 0, and a return value range positive: 0~255, if return-1 means that the end of the file is read to EOF (eof:end of files)! Automatically moves the file pointer after each read to prepare for the next read.

    • Write (byte[] D) method

    • java void write(byte[] d)

Randomaccessfile provides a way to write a set of bytes to a file:

This method writes out all the bytes in the given array consecutively, based on the position of the current pointer, and there is a common method similar to this method:

voidwrite(byte[] d,int offset,int len)

This method writes out a subset of the bytes in the given array consecutively, starting at the position of the current pointer, which starts at the offset of the array and continuously Len bytes.

    • Read (byte[] D) method

    • java int read(byte[] b)
      Randomaccessfile provides a way to bulk read bytes from a file:
      The method attempts to read from the file up to a maximum of bytes of the total length of the given array, starting at the first position of the given byte array, storing the read byte order into the array, and returning the value
      The amount of bytes to actually read.

    • Close method

Randomaccessfile call the Close () method to release all system resources associated with the file access after the operation has finished.

java void close()

For example:

java RandomAccessFile raf = new RandomAccessFile(file,”rw”); …..//读写操作 raf.close();//访问完毕后要关闭以释放系统资源。

?

File pointer operation Getfilepointer method

The read and write operations of Randomaccessfile are pointer-based, which means that they are always read and written at the point where the pointer is currently pointing.
Randomaccessfile provides a way to get the current pointer position:

longgetFilePointer()

Randomaccessfile is created by default to the start of the file (the first byte), and the Getfilepointer method gets the pointer position value as "0".
For example:

  new RandomAccessFile(file,”rw”);  System.out.println(raf.getFilePointer());//0  raf.write(‘A’);//写出一个字节后,指针自动向后移动到下一个字节位置  System.out.println(raf.getFilePointer());//1  raf.writeInt(3);  System.out.println(raf.getFilePointer());//5  raf.close();
Seek method

Randomaccessfile provides a way to move the pointer position.

voidseek(long pos)

Use this method to move the pointer to the specified position.
For example:

  new RandomAccessFile(file,”rw”);  System.out.println(raf.getFilePointer());//0  raf.write(‘A’);//指针位置1  raf.writeInt(3);//指针位置5  raf.seek(0);//将指针移动到文件开始处(第一个字节的位置)  System.out.println(raf.getFilePointer());//0  raf.close();
Skipbytes method

Randomaccessfile provides a way to attempt to skip the input n bytes to discard the skipped bytes, as defined by the method:

intskipBytes(int n)

The method may skip some small number of bytes (possibly including 0). This can be caused by any number of conditions, and the end of the file is reached before skipping N bytes.
Yes. This method does not throw eofexception. Returns the actual number of bytes skipped. If n is a negative number, no bytes are skipped.

Java file Operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.