Java IO stream: Random file read/write, javaio stream

Source: Internet
Author: User

Java IO stream: Random file read/write, javaio stream

The Java. io package provides the RandomAccessFile class for creating and accessing random files. Using this class, you can jump to any position of the file to read and write data. The program can insert data into a random file without damaging other data of the file. In addition, the program can also update or delete the previously stored data without overwriting the entire file.

Two construction methods of the RandomAccessFile class:

Mode indicates the operation status of the created random read/write file:
R: Indicates opening a file in read-only mode.
Rw: Indicates opening a file in read/write mode. In this mode, only one object can be used to simultaneously perform read/write operations.

Next we will simulate the system log and write the data to the end of the file.

Import java. io. *; public class TestRandom {public static void main (String args []) throws IOException {try {BufferedReader in = new BufferedReader (new InputStreamReader (System. in); String s = in. readLine (); RandomAccessFile myFile = new RandomAccessFile ("f: \ java \ TestRandom. log "," rw "); myFile. seek (myFile. length (); // move to the end of the file myFile. writeBytes (s + "\ n"); // write data to myFile. close () ;}catch (IOException e ){}}}
After the program runs, create a TestRandom. log file in the directory. The entered content will be added at the end of the file each time it runs.

The input and output operations can receive information from the outside world or transmit the information to the outside world. Java implements these input and output operations using a stream and represents them through a unified interface, making the program design simpler.



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.