Java input and output stream

Source: Internet
Author: User


2015/9/7 16:59:33
NoBody 2015/9/7 16:59:33

Https://office.inspur.com/eportal/ui?pageId=334521&fromUrl= ahr0chm6ly9vzmzpy2uuaw5zchvylmnvbs9lcg9ydgfsl3vpp3bhz2vjzd0zmjk4odq=
6:25:54
NoBody 2015/9/9 6:25:54

To] (go from blog Park) Java file Operations---file read and write examples
2012-3-21 Read 3357 Comments 0

Original link:

Http://www.cnblogs.com/springcsc/archive/2009/12/03/1616367.html



Although the concept of flow, but this concept for beginners, is still relatively abstract, the following with the actual reading of the file as an example, introduces the concept of flow, as well as the basic use of the input stream.

According to the knowledge described earlier, the data in the file is read into the program, is the program external data into the program, you should use the input stream--inputstream or reader. And because the read is a specific data source-the file, you can use the input corresponding subclass FileInputStream or FileReader implementation.

When you actually write your code, you need to familiarize yourself with the process of reading the file in your program. In the Java language IO programming, reading a file is a two-step process:

1. Convert the data in the file to a stream.

2. Read the data inside the stream.

The first step is completed by the system, only need to create the corresponding stream object, the object is created after the completion of Step 1, the second step is implemented using the Read method in the input stream object.



When programming with an input stream, the code is generally divided into 3 parts:

1. Create a Stream object.

2. Read the data inside the stream object.

3. Close the Stream object.



The following code example reads a file:



Import java.io.*;

/**
* Read files using FileInputStream
*/

public class ReadFile1 {

public static void Main (string[] args) {

Declaring a Stream object
FileInputStream FIS = null;

try{
Creating a Stream object
FIS = new FileInputStream ("E:\\a.txt");

Reads the data and stores the read data in an array
byte[] data = new byte[1024]; Array of data stores
int i = 0; Current subscript

Reads the first byte of data in a stream
int n = fis.read ();
Read the subsequent data sequentially
while (n! =-1) {//does not reach the end of the stream
To store valid data in an array
Data[i] = (byte) n;
Subscript Increase
i++;
Read the next byte of data
n = fis.read ();
}
Parsing data
string s = new string (data,0,i);
Output string
System.out.println (s);
}catch (Exception e) {
E.printstacktrace ();
}finally{
try{
Close the stream and release the resource
Fis.close ();
}catch (Exception e) {}
}
}
}

In the sample code, first create an object of type FileInputStream FIS:

FIS = new FileInputStream ("E:\\a.txt");

This establishes a stream that connects to the data source E:\a.txt and converts the data from that data source to the Stream object FIS, which later reads the data from the data source and only needs to be read from the Stream object fis.

Reading the data in the stream FIS requires the Read method, which is a method inherited from the InputStream class, which is used to read one byte of the stream each time, and if you need to read all the data in the stream, you need to use a circular read when the end of the stream is reached. The return value of the Read method is-1.

In this example, the first byte in the stream is read first:

int n = fis.read ();

and assigns the read value to the INT value n, if the stream fis is empty, then the value of n is-1, otherwise the last byte in N contains the first byte in the stream FIS, and after that byte is read, it is removed from the stream fis.

It then loops through the other data in the stream, and if the data read is not-1, the data already read n is cast to Byte, which takes the valid data in N-the last byte, and stores it in the array data. The Read method in the Stream object FIS is then called to continue reading the data for the next byte in the stream. This loop continues until the data read is-1, which is the end of the loop that reads to the end of the stream.

The array length here is 1024, so the data in the stream cannot be longer than 1024, so the sample code has some limitations here. If the number of data flow is more, you can expand the 1024 to the appropriate number.



After the above loop, the data in the stream can then be stored in a sequence in the data array, the number of valid data stored in the data array is I, that is, the number of cycles.

In fact, up to here, the IO operation in the read data has been completed, and then according to the data source data format, here is the format of the file, parse the read byte array can be.

The parsing in the sample code simply converts the valid data that is read from the stream object, which is the first n in the data array, into a string, and then outputs it.

In the example code, just output the exception information in the Catch statement, easy to debug the code, in the actual program, it is necessary to do some logical processing, such as giving the prompt information.

Finally, in the finally statement block, close the Stream object FIS, release the resources occupied by the stream object, close the data source, and realize the end of the flow operation.



The above details the process of reading the file, in fact, while actually reading the stream data, you can also use the other Read method, the following example code is to use another read method to implement the read code:



Import Java.io.FileInputStream;

/**
* Read files using FileInputStream
*/
public class ReadFile2 {
public static void Main (string[] args) {
Declaring a Stream object
FileInputStream FIS = null;
try{
Creating a Stream object
FIS = new FileInputStream ("E:\\a.txt");
Reads the data and stores the read data in an array
byte[] data = new byte[1024]; Array of data stores
int i = fis.read (data);
Parsing data
string s = new string (data,0,i);
Output string
System.out.println (s);
}catch (Exception e) {
E.printstacktrace ();
}finally{
try{
Close the stream and release the resource
Fis.close ();
}catch (Exception e) {}
}
}
}


In the sample code, only one line of code is used:

int i = fis.read (data);

It is implemented to read data from the Stream object FIS into the byte array data. The purpose of this line of code is to read the data in the FIS stream and store it in the array data sequentially, returning the value to the actual number of valid data read.

You can simplify the read code by using this method when reading.

Of course, when you read a file, you can also use the subclass FileReader of the reader class to do it, and when you write your code, you only need to replace the byte array in the sample code above with a char array.

When reading a file using FileReader, it is read in char, so it is more suitable for reading text files, and for binary or custom format files, it is easy to parse and manipulate the read data by using FileInputStream for reading.

While reading other data sources is similar to reading a file, the biggest difference is that the classes selected when the Stream object is created are different, and once the stream object is established, the basic reading method is the same, and if only the most basic read method is used, the use is basically consistent. This is also the purpose of the IO class design, so that the operation of the flow object is consistent, simplifying the use of the IO class difficulty.

Ride.



The basic output stream contains OutputStream and writer two, the difference is that the class in the OutputStream system (that is, the subclass of OutputStream) is written in bytes, and the class in the writer system (that is, the subclass of writer) is written by character.



The steps for programming with the output stream are:

1. Set up the output stream

The corresponding output stream object is established, that is, the conversion between the stream object and the external data source is completed.

2. Write data to the stream

The data that needs to be output is called, and the corresponding write method is written to the stream object.

3. Turn off the output stream



After the write is completed, the Close method of the call flow object closes the output stream and frees the resource.

When using output flow to external output data, the programmer only needs to write the data to the stream object, the underlying API implementation writes the contents of the stream object to the external data source, the writing process is transparent to the programmer and does not need to be written specifically for code implementation.

When outputting data to a file, that is, when writing a file, use the corresponding file output stream, including FileOutputStream and FileWriter two classes, the following FileOutputStream as an example to illustrate the use of the output stream. The sample code is as follows:



Import java.io.*;

/**
* Example of using FileOutputStream to write files
*/
public class WriteFile1 {
public static void Main (string[] args) {
String s = "Java language";
int n = 100;
Declaring a Stream object
FileOutputStream fos = null;
try{
Creating a Stream object
FOS = new FileOutputStream ("E:\\out.txt");
Convert to byte array
Byte[] B1 = S.getbytes ();
Line break
byte[] B2 = "\ r \ n". GetBytes ();
byte[] B3 = string.valueof (n). GetBytes ();
Write to file in sequence
Fos.write (B1);
Fos.write (B2);
Fos.write (B3);
} catch (Exception e) {
E.printstacktrace ();
}finally{
try{
Fos.close ();
}catch (Exception e) {}
}
}
}


The sample code writes a file that is opened with Notepad, with the following content:

Java language

100
In this sample code, it is demonstrated that a string and a value of type int are written sequentially to the same file. When you write to a file, you first create a file output stream object fos:

FOS = new FileOutputStream ("E:\\out.txt");

After the object is created, it implements a connection from the stream to the external data source e:\out.txt. Description: When the external file does not exist, the system automatically creates the file, but an exception occurs if the file path contains a directory that is not created. The file path written here can be either an absolute path or a relative path.

There are two ways to write to a file when it is actually written: Overwrite and append. Where "overwrite" means to clear the contents of the original file, write new content, by default, write the file, "append" refers to the end of the existing file to write content, retain the original file content, such as writing a log file, the general use of append. In practical use, you can use the appropriate form as needed:

Public FileOutputStream (String name, Boolean append) throws FileNotFoundException

You only need to use this construction method to set the value of the second parameter append to True when constructing the FileOutputStream object.

Once the stream object is created, you can write the data sequentially to the stream using the Wirte method provided in OutputStream. The most basic write method supports only byte array format data, so if you need to write the content to the file, you need to first convert the corresponding content to a byte array.

This writes the data in the following format: First writes the string s, converts the string to a byte array using the GetBytes method of the String class, and then writes the string "\ r \ n", in the same way as the string, which implements a newline display of the text file, and finally writes the INT data n, First convert N to a string and then to a byte array. The order in which the data is written and converted to a byte array is the data format of the stream, which is the format of the file. Because this is written in a text file, the contents of the write are displayed in clear text, or you can set a specific file format based on the data you need to store.

In fact, all data files, including picture files, sound files and so on, are stored in a certain data format data, when saving the file, the need to save the data in accordance with the data format of the file to write, and when opening the file, the data read to the file according to the format of the corresponding logic can be resolved.

Finally, when data is written to the inside of the stream, you can use the Flush method of the Stream object if you need to force output of the data inside the write stream to the external data source immediately. If you do not need to force the output, you only need to close the stream object after the write is finished. When you close a Stream object, the system first forces output to the data in the stream that is not output to the data source, and then releases the memory space that the stream object occupies.

When writing to a file using FileWriter, the steps and the actions to create the stream object are consistent with the sample code, except that when you transform the data, you need to convert the written data to a char array, and for a string, you can use the ToCharArray method in string to implement the conversion. Then write the data in the file format.

For other types of byte output stream/character output streams, it is only logical to connect different data sources, there will be a certain difference in the code to create the object, but once the stream object is created, the basic write method is the Write method, You also need to first convert the data you want to write to the corresponding byte array/char array in a certain format, and then write it in turn.

So the IO class design form, only need to be familiar with one of the system in the use of a class, you can comprehend by analogy learn the use of other classes of the same type, thus simplifying the programmer's learning, so that the use of consistency.

Java input and output stream

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.