Java io (File class, byte stream and byte stream, byte character conversion Stream)

Source: Internet
Author: User
Tags array to string
Document directory
  • Main methods and constants in the file class
  • Procedure
  • Byte output stream: outputstream
  • Byte input stream: inputstream
  • Character output stream: writer
  • Character input stream: Reader

 

File class

In the entire Io package, the only class that indicates the file itself is the file class. You can use the File class to create or delete files. To use the File class, you must first observe the construction method of the file class. The common construction methods of this class are as follows:

Public file (string pathname) when instantiating the file class, you must set the path to locate the file according to the path
Main methods and constants in the file class

Method or constant

Type

Description

Public static final string pathseparator

Constant

It indicates the path separator (Windows :';')

Public static final string Separator

Constant

Path separator (Windows :'\')

Public file (string pathname)

Structure

Create a file object and pass in the complete path

Public Boolean createnewfile () throws ioexception

Normal

Create a new file

Public Boolean exists ()

Normal

Determine whether a file exists

Public Boolean Delete ()

Normal

Delete an object

Public Boolean isdirectory ()

Normal

Determines whether the specified path is a directory.

Public long length ()

Normal

Size of the returned File

Public String [] list ()

Normal

Lists all the contents of a specified directory, just the name

Public file [] listfiles ()

Normal

Lists All contents of a specified directory and lists the paths.

Public Boolean mkdir ()

Normal

Create a directory

Public Boolean renameto (File DEST)

Normal

Rename an existing file

Sample Code:

Import Java. io. *; public class filedemo01 {public static void main (string ARGs []) {file = new file ("D:" + file. separator + "test.txt"); system. out. println ("file. pathseparator: "+ file. pathseparator); // call the static variable system. out. println ("file. separator: "+ file. separator); // call the static variable if (file. exists () {// checks whether the current file exists. delete (); // Delete if yes} Try {file. createnewfile (); // Delete and recreate} catch (ioexception e) {e. printstacktrace ();} system. out. println ("file size:" + file. length (); // output the size of the newly created file }}

Sample Code 2:

Import Java. io. *; public class filedemo02 {public static void main (string ARGs []) {file = new file ("D:" + file. separator + "test"); file. mkdir (); // create a new folder file F = new file ("D:" + file. separator + "test.txt"); F. renameto (new file ("D:" + file. separator + "test1.txt"); // rename a known file }}

Case: list all objects in a specified directory

Import Java. io. file; import Java. io. ioexception; public class filedemo03 {public static void main (string ARGs []) {file my = new file ("D:" + file. separator); // operation path print (my);} public static void print (File file) {// recursively call if (file! = NULL) {// determines whether the object is null if (file. isdirectory () {// If the directory is file F [] = file. listfiles (); // list all objects if (F! = NULL) {// determines whether this directory can list for (INT I = 0; I <F. length; I ++) {print (F [I]); // continue to judge because the given path may be a directory.} else {system. out. println (File); // output path }}}};
Byte stream and byte stream

There are two main types of file content in the Java. Io package: byte stream and byte stream. Both types are input and output operations. Output Data in the byte stream is mainly completed using outputstream, inputstream is used for input, and writer class is used for output in the bytes stream, and reader class for input.

Stream

All data in the program is transmitted or saved as a stream. When the program needs data, it needs to use the input stream to read the data. When the program needs to save some data, the output stream is required.

Procedure

I/O operations in Java are also related steps. Taking file operations as an example, the main operation process is as follows:

• A. Use the file class to open a file • B. Specify the output position through the byte stream or the byte stream subclass • C. Perform read/write operations • D. Disable input/output.
Byte stream

Byte streams are mainly used to operate byte data, and the byte array prevails. The main operation class is

· Byte output stream: outputstream

· Byte input stream: inputstream

Byte output stream: outputstream

The outputstream class is the largest parent class of the byte output stream in the entire Io package. Its definition is as follows:

Public abstract class outputstream extends object implements closeable, flushable • closeable: indicates the operation that can be closed, because the program must be closed at the end. • Flushable: Indicates refreshing and clearing data in the memory.

From the definition of the above class, we can find that this class is an abstract class. If you want to use this class, you must first instantiate the object through the subclass. If you want to operate a file now, you can use the fileoutputstream class. After the upward transformation, You Can instantiate outputstream.

Common methods in the outputstream class:

Method description public void close () throws ioexception close output stream public void flush () throws ioexception refresh buffer public void write (byte [] B) throws ioexception writes a byte array to the data stream public void write (byte [] B, int off, int Len) throws ioexception writes a specified byte array to the data stream public abstract void write (int B) throws ioexception writes one byte to the data stream

To use the above method, you must use the subclass for instantiation. In this case, use the fileoutputstream subclass. The constructor of this class is as follows:

public FileOutputStream(File file) throws FileNotFoundException

Code example: create a file and write characters

Import Java. io. *; public class outputstreamdemo01 {public static void main (string ARGs []) throws exception {// 1. Use the file class to specify a file name file = new file ("D: "+ file. separator + "test.txt"); // 2. Create an outputstream class and instantiate the object outputstream out = new fileoutputstream (File ); // 3. Execute the write operation string STR = "Hello World"; byte B [] = Str. getbytes (); out. write (B); // 4. Close the input stream out. close ();}}

Note:

1. If the file does not exist during the operation, a new file is automatically created for the user.

2. If the content to be appended needs a line break, add "\ r \ n" to the content.

After the above operations write data, the content before the file does not exist, because in the IO operation, it is overwritten by default. If you want to perform the append function, you must set the append operation. In this case, you can use fileoutputstream to Append content to the file: another constructor of fileoutputstream:

FileOutputStream(File file, boolean append)

In the constructor, if the value of append is set to true, content is appended to the end of the file.

OutputStream out=new FileOutputStream(file,true);
Byte input stream: inputstream

Since the program can write content to the file, it can read the content from the file through inputstream. First, let's look at the definition of the inputstream class:

public abstract class InputStream extends Object implements Closeable

Like outputstream, inputstream itself is also an abstract class and must rely on its subclass. If it is read from a file, the subclass must be fileinputstream. Constructor:

public FileInputStream(File file) throws FileNotFoundException
Common Methods of the inputstream class: Method description public int available () throws ioexception can be used to obtain the size of the input file public void close () throws ioexception close input stream public abstract int read () throws ioexception reads the content, reads the public int read (byte [] B) throws ioexception by number, reads the content to the byte array, and returns the number

Sample Code:

Import Java. io. file; import Java. io. inputstream; import Java. io. fileinputstream; public class inputstreamdemo01 {public static void main (string ARGs []) throws exception {// thrown out of an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 1. instantiate the parent class Object inputstream input = NULL through subclass; // prepare an input object input = new fileinputstream (f); // Through object polymorphism, perform instantiation // Step 2 and read byte B [] = new byte [3rd]; // all the content is read into the input in this array. read (B); // read the content. // Step 3: Close the output stream input. close (); // close the output stream system. out. println ("content:" + new string (B); // convert the byte array to string output }};

The code above reads the content of the file, but the space opened by the array is much larger than the space occupied by the file. In this case, the array space can be opened based on the size of the file to be read:

Import Java. io. file; import Java. io. inputstream; import Java. io. fileinputstream; public class inputstreamdemo03 {public static void main (string ARGs []) throws exception {// thrown out of an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 1. instantiate the parent class Object inputstream input = NULL through subclass; // prepare an input object input = new fileinputstream (f); // Through object polymorphism, instantiate // Step 2 and perform read Operations // byte B [] = new byte [input .. available ()]; same as using the following code, byte B [] = new byte [(INT) F. length ()]; // The array size is determined by the file int Len = input. read (B); // read the content. // Step 3: Close the output stream input. close (); // close the output stream \ system. out. println ("length of data read:" + Len); system. out. println ("content:" + new string (B); // convert the byte array to string output }};

Another reading method:

Import Java. io. file; import Java. io. inputstream; import Java. io. fileinputstream; public class inputstreamdemo05 {public static void main (string ARGs []) throws exception {// thrown out of an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 1. instantiate the parent class Object inputstream input = NULL through subclass; // prepare an input object input = new fileinputstream (f); // instantiate the object through object polymorphism // Step 1 and perform read Operations byte B [] = new byte [ 1024]; // The array size is determined by the file's int Len = 0; int temp = 0; // receives each read data while (temp = input. Read ())! =-1) {// indicates that there is still content. The file has not read step B [Len] = (byte) temp; Len ++;} // 4th. Close the output stream input. close (); // close the output stream \ system. out. println ("content:" + new string (B, 0, Len); // convert the byte array to string output }};

The preceding reading methods are common.

Ghost stream

If a character in the program is equal to 2 bytes, Java provides two classes specifically used to operate the volume stream: reader and writer.

· Character output stream: writer

· Character input stream: Reader

Character output stream: writer

Writer itself is an output class of a volume stream. The definition of this class is as follows:

public abstract class Writer extends Object implements Appendable, Closeable, Flushable

This class is also an abstract class. If you want to use this class, you must use its subclass. If you want to write content to the file, you should use the filewriter subclass. The constructor is as follows:

public FileWriter(File file) throws IOException

Common writer methods:

Method or constant description public abstract void close () throws ioexception close output stream public void write (string Str) throws ioexception output string public void write (char [] cbuf) throws ioexception outputs the character array public abstract void flush () throws ioexception mandatory clear Cache

Sample Code: (the bytes stream can directly output strings without converting them to bytes)

Import Java. io. file; import Java. io. writer; import Java. io. filewriter; public class writerdemo01 {public static void main (string ARGs []) throws exception {// thrown by an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 4. instantiate the parent class Object writer out = NULL through subclass; // prepare an output object out = new filewriter (f); // instantiate the object through object polymorphism. // Step 4: Perform the write operation string STR = "Hello world !!! "; // Prepare a string out. write (STR); // output the content, save the file // step 3, and close the output stream out. close (); // close the output stream }};

If you want to append the content in the same format as fileinputstream, add the appemd attribute to true;

Character input stream: Reader

Reader itself is an input class of the livestream. The definition of this class is as follows:

public abstract class Reader extends Object implements Closeable, Readable;

This class is also an abstract class. If you want to use this class, you must use its subclass. If you want to write content to the file, you should use the filereader subclass. The constructor is as follows:

public FileReaderr(File file) throws IOException

Common writer methods:

Method or constant description public abstract void close () throws ioexception close output stream public int read () throws ioexception read single character public int read (char [] cbuf) throws ioexception reads the content into the string array and returns the read length.

Sample Code: (read and retrieve data in the form of a character array)

Import Java. io. file; import Java. io. reader; import Java. io. filereader; public class readerdemo01 {public static void main (string ARGs []) throws exception {// thrown out of an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 1. instantiate the parent class Object Reader Input = NULL through subclass; // prepare an input object input = new filereader (f); // Through object polymorphism, instantiate // Step 2 and read char C [] = new char [3rd]; // read all the content in this array, int Len = input. read (c); // read the content. // Step 3: Close the output stream input. close (); // close the output stream system. out. println ("content:" + new string (C, 0, Len); // convert the character array to string output }};

The byte stream itself does not use the buffer (memory) during operations. It operates directly with the file itself, while the swap stream uses the buffer during operations.

Verify that the ghost stream uses the cache through code.

Import Java. io. file; import Java. io. outputstream; import Java. io. fileoutputstream; public class outputstreamdemo05 {public static void main (string ARGs []) throws exception {// thrown out of an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 4. instantiate the parent class Object outputstream out = NULL through subclass; // prepare an output object out = new fileoutputstream (f); // instantiate // Step 4: Write string STR = "Hello world !!! "; // Prepare a string byte B [] = Str. getbytes (); // only the byte array can be output, so the string is changed to the byte array out. write (B); // write data // step 3 close the output stream // out. close (); // close the output stream. The output stream is not closed here }};

In byte stream operations, even if it is not closed, it can be output.

Import Java. io. file; import Java. io. writer; import Java. io. filewriter; public class writerdemo03 {public static void main (string ARGs []) throws exception {// thrown by an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 4. instantiate the parent class Object writer out = NULL through subclass; // prepare an output object out = new filewriter (f); // instantiate the object through object polymorphism. // Step 4: Perform the write operation string STR = "Hello world !!! "; // Prepare a string out. write (STR); // output the content, save the file // step 3, and close the output stream // out. close (); // at this time, it is not closed }};

The preceding content does not output any content. That is to say, all content is stored in the buffer zone. If the output stream is disabled, the buffer zone is refreshed forcibly, therefore, you can output the content.

If it is assumed that the refresh method is not disabled, You can manually call the refresh method as follows:

public void flush() throws IOException

Sample Code:

Import Java. io. file; import Java. io. writer; import Java. io. filewriter; public class writerdemo04 {public static void main (string ARGs []) throws exception {// thrown by an exception, do not process // Step 3. Use the file class to find a file F = new file ("D:" + file. separator + "test.txt"); // declare the file object // Step 4. instantiate the parent class Object writer out = NULL through subclass; // prepare an output object out = new filewriter (f); // instantiate the object through object polymorphism. // Step 4: Perform the write operation string STR = "Hello world !!! "; // Prepare a string out. write (STR); // output the content, save the file // step 3, and close the output stream out. flush (); // forcibly clear the content in the buffer. // out. close (); // at this time, it is not closed }};

All files stored on the hard disk or transmitted in bytes. Images are also completed in bytes, while characters are only formed in memory. Therefore, there are many bytes of operation in development.

Example: copy a file

Run this program to copy the source file to the target file:

Import java. Io. *; public class copy {public static void main (string ARGs []) {If (ARGs. length! = 2) {// check whether the two parameters system. Out. println ("are incorrect. "); System. out. println ("Example: Java copy source file path destination file path"); system. exit (1); // system exit} file F1 = new file (ARGs [0]); // file object of the source file: file F2 = new file (ARGs [1]); // If (! F1.exists () {system. Out. println ("the source file does not exist! "); System. exit (1);} inputstream input = NULL; // prepare the input stream object and read the source file outputstream out = NULL; // prepare the output stream object, write the target file try {input = new fileinputstream (F1);} catch (filenotfoundexception e) {e. printstacktrace ();} Try {out = new fileoutputstream (F2);} catch (filenotfoundexception e) {e. printstacktrace ();} If (input! = NULL & out! = NULL) {// determine whether the input or output is ready int temp = 0; try {While (temp = input. Read ())! =-1) {// Start copying out. Write (temp); // read and write} system. Out. println ("Copy completed! ");} Catch (ioexception e) {e. printstacktrace (); system. Out. println (" Copy failed! ");} Try {input. close (); // close out. close (); // close} catch (ioexception e) {e. printstacktrace ();}}}}
Byte-character conversion streams outputstreamwriter and inputstreamreader

In the entire Io package, it is actually a byte stream and a batch stream, but in addition to these two streams, there is also a set of byte stream-Batch stream conversion classes.

• Outputstreamwriter: a subclass of writer that converts the output bytes stream to a byte stream. That is, to convert the output object of a byte stream to the output object of the byte stream • inputstreamreader: a subclass of reader, which converts the input byte stream to the bytes stream, that is: changes the input object of a byte stream to the input object of a byte stream.

In the outputstreamwriter class, an object of a byte stream is required: Public outputstreamwriter (outputstream out). For example, the object outputs a byte file stream as a character.

Import Java. io. *; public class outputstreamwriterdemo01 {public static void main (string ARGs []) throws exception {// All exceptions Throw file = new file ("D:" + file. separator + "test.txt"); writer = NULL; // character output stream writer = new outputstreamwriter (New fileoutputstream (File )); // The byte stream is converted to the bytes stream string STR = "Hello world !!!! "; Writer. Write (STR); // use the response stream to output writer. Close ();}}

When reading, you can also use the byte stream to read the file of the byte stream.

Import Java. io. *; public class inputstreamreaderdemo01 {public static void main (string ARGs []) throws exception {file F = new file ("D:" + file. separator + "test.txt"); reader = NULL; reader = new inputstreamreader (New fileinputstream (f )); // convert the byte stream to the bytes stream char C [] = new char [1024]; int Len = reader. read (c); // read reader. close (); // close system. out. println (new string (C, 0, Len ));}};

Description of filewriter and filereader:

From the JDK documentation, we can see that fileoutputstream is the direct subclass of outputstream, and fileinputstream is also the direct subclass of inputstream. However, there are some special operation classes in the worker stream file, and filewriter is not the subclass of writer, it is a subclass of outputstream, and filereader is not a direct subclass of reader, it is a subclass of inputstreamreader.

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.