Java basics-I/O (3) and java basics I/O

Source: Internet
Author: User

Java basics-I/O (3) and java basics I/O

1. Pipeline Flow

Demo: PipedInputStream and PipedOutputStream

Note: Pipeline streams are not recommended in one thread because the data written to the output stream is saved to an array of 1024 bytes in the input stream, if the written content exceeds the size of this array and is not read by the input stream, the thread where the output stream is located will wait. If it is in the same thread, this thread will be deadlocked and is not recommended in the same thread. (API)

Import java. io. IOException; import java. io. pipedInputStream; import java. io. pipedOutputStream; public class Test17 {public static void main (String [] args) throws IOException, InterruptedException {Sender sender = new Sender (); extends er extends ER = new worker Er (); pipedOutputStream out = sender. getOut (); PipedInputStream in = cycler. getIn (); in. connect (out); // out. connect (in); // This can also be sender. start (); Thread. sleep (10); sleep er. start () ;}// Sender class Sender extends Thread {private PipedOutputStream out = new PipedOutputStream (); public void run () {try {int I = 1; while (true) {Thread. sleep (2000); String msg = "Hello, this is the message" + I ++ "; out. write (msg. getBytes () ;}} catch (Exception ex) {ex. printStackTrace () ;}} public PipedOutputStream getOut () {return this. out ;}// Receiver class extends er extends Thread {private PipedInputStream in = new PipedInputStream (); public void run () {try {while (true) {byte [] buff = new byte [1024]; int len = in. read (buff); String str = new String (buff, 0, len); System. out. println (str) ;}} catch (Exception ex) {ex. printStackTrace () ;}} public PipedInputStream getIn () {return this. in ;}// Pipe closed occurs when the pipeline is closed and the sender is still sending

Ii. File cutting and merging

Public static void merget2 () throws Exception {OutputStream out = new FileOutputStream ("c:/src_new.zip"); BufferedOutputStream bos = new BufferedOutputStream (out); for (int I = 1; I <= 20; I ++) {InputStream in = new FileInputStream ("c:/src _" + I); byte [] buff = new byte [in. available ()]; in. read (buff); bos. write (buff); in. close ();} bos. close (); System. out. println ("merged successfully");} public static void merge () throws Exception {OutputStream out = new FileOutputStream ("c:/src_new.zip"); for (int I = 1; I <= 20; I ++) {InputStream in = new FileInputStream ("c:/src _" + I); byte [] buff = new byte [in. available ()]; in. read (buff); out. write (buff); in. close ();} out. close (); System. out. println ("merged successfully ");}

Iv. File Overview

A stream can only operate on data.

The File class is the only class in the IO package that represents the disk File itself.

File defines some platform-independent methods to operate files.

File: the abstract representation of the File and directory path. // The path is also a file

Used to encapsulate files or folders into objects.

Convenient operations on file and folder attributes

File object. The constructor that is often used as a parameter to pass to the stream.

The File class cannot access the File content, that is, it cannot read or write data from the File. It can only operate on the attributes of the File.

5. Common File Operations

Boolean createNewFile () // create a new file. If the file is successfully created, true is returned. Otherwise, false is returned. If the file already exists, false is returned, which is different from the stream and overwrites the stream.

Mikdir () mikdirs // create a directory, which can create multi-level Directories

Boolean delete () // delete the file or directory represented by this abstract path name. If the path name indicates a directory, the directory must be empty before deletion. Otherwise, false is returned.

Void deleteOnExit () // when the VM is terminated, delete the file or directory. Note that its return type is void because the VM is terminated. Of course, the return value is useless.

Exists () // test whether the file or directory represented by this abstract path name exists.

IsDirectory () // determine whether it is a directory

IsFile () // determine whether it is a file

IsHidden () // checks whether the object is hidden.

Static void fileDemo () throws IOException {File f1 = new File ("1.txt"); // File f2 = new File (" c: \ 2.txt") in the current path "); file f3 = new File ("c: \", "3.txt"); File f4 = new File (" c: \ "); File f5 = new File (f4, "5.txt"); // File (File parent, String child)/* f1.createNewFile (); f2.createNewFile (); f3.createNewFile (); System. out. println (f4.createNewFile (); // return false f5.createNewFile (); * // * System. out. println (f1.delete (); // true System. out. println (f2.delete (); // true System. out. println (f3.delete (); // true System. out. println (f4.delete (); // false System. out. println (f5.delete (); // true * // System. out. println (new File ("c:/aaa "). delete (); // (aaa is a folder) If there is content under aaa, false is returned; otherwise, true is returned, and delete the folder/* File f = new File ("c: \ BBBSSS \ 1.txt \ cc \ dd "); // In this example, 1.txt will also be used as the folder name f. mkdirs (); // when creating multiple levels, use mkdirs (); new File ("c:/forlder1 "). mkdir (); // only the first-level directory can be created * // * File ff = new File ("c: \ nonexistent File .txt"); System. out. println (ff. isDirectory (); // false System. out. println (ff. isFile (); // false System. out. println (ff. isHidden (); // false * // * File ff = new File ("c: \ nonexistent File .txt"); ff. createNewFile (); System. out. println (ff. isDirectory (); // false System. out. println (ff. isFile (); // true System. out. println (ff. isHidden (); // false */File ff = new File ("c: \ nonexistent File .txt"); ff. mkdir (); System. out. println (ff. isDirectory (); // true System. out. println (ff. isFile (); // false System. out. println (ff. isHidden (); // false // note that for files, folders, isDirectory, and isFile that have not been created, false is returned. To obtain the correct result, you must first use exists to determine the result}

6. File Operations

String getName (); // name of the returned file or directory

String getParent (); // returns the name of the parent directory. If no value exists, null is returned.

String getPath (); // return path String ??? File name included

String getAbsolutePath (); // returns the absolute path name String

// File getAbsoluteFile (); // returns the absolute path name. Equivalent to new File (this. getAbsolutePath ())

Long length (); // The length of the returned file, in bytes

Static File [] listRoots () // list available File systems. In windows, drive letters such as c d e are listed.

String [] list () // returns the files and directories in the directory (that is, returned together with the file name) (hidden files will also be returned)

String [] list (FilenameFilter filter) // returns the files and directories filtered by the specified filter.

File [] listFiles () // return all files in the current directory

File [] listFiles (FilenameFilter filter)

Public static void fileInfoDemo () {File f = new File ("c: \ Test \ 1.txt"); System. out. println ("getName --" + f. getName (); // 1.txt System. out. println ("getParent () --" + f. getParent (); // c: \ Test System. out. println ("getPath () --" + f. getPath (); // c: \ Test \ 1.txt System. out. println ("getAbsolutePath --" + f. getAbsolutePath (); // c: \ Test \ 1.txt System. out. println ("length () --" + f. duration (); // 1234 File [] fileList = File. listRoots (); for (File file: fileList) {System. out. println (file); // print C: \ D: \ and so on }}
If you replace the above File path with File f = new File ("1.txt"); // use a relative path, the result is: getName--1.txt getParent () -- null getpath(%--1.txt getAbsolutePath -- C: \ workspace \ Lession21 \ 1.txt length () -- 0 A: \ C: \ D: \ E :\
// Display all static void listDemo () {File f = new File ("C:/folder A/"); String [] nameList = f. list (); for (String str: nameList) {System. out. println (str );}}
// Example: static void filterDemo () {File f = new File ("C:/folder A/ Emy thesis collection/ 文 ") with filtering "); file [] fileList = f. listFiles (new FilenameFilter () {public boolean accept (File dir, String name) {return! Name. endsWith (". exe "); // only view the exe File}); for (File item: fileList) {System. out. println (item. getName ());}}

VII. Recursive operations
Recursively view contents in the directory

Public static void main (String [] args) {recuDir (new File ("C: \ job \ 8.13");} static void recuDir (File dir) {System. out. println ("------------------"); File [] fileList = dir. listFiles (); for (File f: fileList) {if (f. isDirectory () {recuDir (f); // recursive call} else {System. out. println (f. getName ());}}}

8. RandomAccessFile

The most functional file handler class in java

Supports "Random Access"

You can jump to any location of the file to read and write data.

This type of object has an indicator pointing to the current read/write position. After reading and writing n Bytes, the file indicator points to the next byte of the n bytes.

When the file is opened, the indicator points to the beginning of the file, you can move the indicator to a new location

It has a great advantage in the random reading of long record format files, but it is limited to Operating Files and cannot access other io devices, such as networks and memory images.

RandomAccessFile Constructor

New RandomAccessFile (f, "rw"); // read/write method (created if the object does not exist)

New RandomAccessFile (f, "r"); // read-only mode

Public static void main (String [] args) throws IOException {final int LEN = 8;/* Student stu1 = new Student (20, "cat "); student stu2 = new Student (21, "sheep"); Student stu3 = new Student (15, "duck"); RandomAccessFile r = new RandomAccessFile ("c:/stu.txt ", "rw"); r. write (stu1.name. getBytes (); r. writeInt (stu1.age); r. write (stu2.name. getBytes (); r. writeInt (stu2.age); r. write (stu3.name. getBytes (); r. writeInt (stu3.age); r. close (); */RandomAccessFile read = new RandomAccessFile ("c:/stu.txt", "rw"); read. skipBytes (12); // skip the information of the first student. The age is 4 bytes and the name is 8 bytes. out. println ("second student information:"); String str = ""; for (int I = 0; I <LEN; I ++) {str ++ = (char) read. readByte ();} System. out. println ("name:" + str); System. out. println ("age:" + read. readInt (); System. out. println ("first student information:"); read. seek (0); str = ""; for (int I = 0; I <LEN; I ++) {str + = (char) read. readByte ();} System. out. println ("name:" + str); System. out. println ("age:" + read. readInt (); System. out. println ("Third Student Information:"); read. skipBytes (12); str = ""; for (int I = 0; I <LEN; I ++) {str + = (char) read. readByte ();} System. out. println ("name:" + str); System. out. println ("age:" + read. readInt (); read. close ();}

9. Detailed description of the Properties class

Properties is a subclass of HashTable. It adds the function of saving keys and values to the stream or reading from the stream. If you want to use the properties. store () method to store the object content, the keyword and value must be String type. You can load the key-Value Pair information from the stream void load (InputStream inStream) to read the attribute list (key-and element-Pair) from the input stream ).
Set <String> stringPropertyNames () returns the key Set in this attribute list.
Note: Try not to use Chinese Characters

Public static void main (String [] args) throws IOException {Properties settings = new Properties (); settings. load (new FileInputStream ("c:/config. ini "); System. out. println (settings. getProperty ("port"); // 8080 // Set from the stream <String> set = settings. stringPropertyNames (); // obtain all attributes for (String key: set) {System. out. println (key + ":" + settings. getProperty (key);} // enter settings. setProperty ("niceCat", "this is a niceCat"); settings. store (new FileOutputStream ("c:/config. ini ")," this is note "); System. out. println ("OK ");}

 

Related Article

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.