Java notes: Java stream, file, and IO

Source: Internet
Author: User
Tags stringbuffer

Update Time: 2018-1-7 12:27:21

For more information, see the online anthology: http://android.52fhy.com/java/index.html

java.ioThe package contains almost all the required classes for operation input and output. All of these flow classes represent the input source and output destination.

Introduction to input and output streams

A stream is defined as a data series. The input stream is used to read data from the source, and the output stream is used to write data to the target.

is a class-level diagram that describes the input stream and the output stream:

In the java.io package to manipulate the contents of the main two major categories: byte stream, character stream, two categories are divided into input and output operations.

The output data in the byte stream is mainly used OutputStream to complete, the input is made InputStream ; the output in the character flow is mainly done using the Writer class, and the input stream is mainly used by the Reader class. These four are abstract classes.

A package dedicated to the input-output functionality is available in Java java.io , including:

    • InputStream, OutputStream , Reader , Writer .
    • InputStreamAnd OutputStream , the two are designed for byte streams and are primarily used to process bytes or binary objects.
    • ReaderAnd Writer , the two are designed for character streams (1 characters in 2 bytes) and are primarily used to handle characters or strings.

The common System.in is actually InputStream object.

Byte stream converted to character stream

To facilitate the processing of byte streams, we often convert the byte stream to a character stream. For example:

Java console input is done by System.in . To get a character stream bound to the console, we can wrap it System.in in an BufferedReader object to create a character stream.

Here is BufferedReader the basic syntax for creating:

new BufferedReader(new InputStreamReader(System.in));

Similarly, read from a file:

new FileInputStream("C:/java/hello"new BufferedReader(new InputStreamReader(f));

The BufferedReader is used to use the buffering function.

java.io.BufferedReaderAnd java.io.BufferedWriter classes each have a buffer of 8192 characters. When BufferedReader reading a text file, the character data is first read from the file and placed in the buffer, and then, if the method is used, it is read() read from the buffer first. If the buffer data is not enough to be read from the file, the data that is BufferedWriter written is not first exported to the destination, but is first stored in the buffer. If the data in the buffer is full, the destination is written out one at a time.

For a simple description of the three classes in the example above:

    • InputStream: is a superclass of all byte input streams, which generally uses its subclasses: and FileInputStream so on, it can output byte stream;
    • InputStreamReader: It is a bridge between byte stream and character stream, can output character stream as character stream, and can specify character set for byte stream, and can output characters.
    • BufferedReader: Provides a common buffered text read, readLine() reads a line of text, reads text from the character input stream, buffers individual characters, and provides efficient reading of characters, arrays, and rows.

InputStreamProvides read() methods that support reading a data byte from the input stream. Common prototypes:

publicintreadthrows IOException {}

Reads a byte of data from this input stream. If no input is available, this method will block.
Specified by: Read in class InputStream
Returns: The next data byte, or 1 if the end of the file has been reached.

publicintread(bytethrows IOException{}

Reads a maximum of b.length bytes of data from this input stream into a byte array. This method will block until some of the inputs are available.
Overwrite: Read in class InputStream
Parameters: A buffer that stores read data.
Returns: The total number of bytes read into the buffer, or 1 if there is no more data since the end of the file has been reached.

Example 1: Read single character input from the console
publicstaticvoidmainthrows IOException{    new BufferedReader(new InputStreamReader(System.in));    char c;        System.out.println("输入字符,按下 'q' 键退出:");        do {        c = (char) br.read();        System.out.println(c);    }while(c != 'q');}
Example 2: Read multi-character input from the console
publicstaticvoidmainthrows IOException{    new BufferedReader(new InputStreamReader(System.in));    String s;    System.out.println("输入字符串,按下 'quit' 键退出:");        do {        s = br.readLine();        System.out.println(s);    }while(!s.equals("quit"));}
Example 3: Reading a byte stream using read in InputStream
 Public Static void Main(string[] args)throwsioexception{InputStream input = System.inch;byte[] B =New byte[1024x768];intLen =0; StringBuffer SB =NewStringBuffer (""); while(len = input.Read(b))! =2) {System. out.println(LEN); Sb.Append(NewString (b,0, Len)); } input.Close(); System. out.println(sb.)toString());}

In fact, it is better to change the example to a file read:

 Public Static void Main(string[] args)throwsioexception{InputStream input =NewFileInputStream ("Src/test.txt");byte[] B =New byte[1024x768];intLen =0; StringBuffer SB =NewStringBuffer (""); while(len = input.Read(b) >0) {System. out.println(LEN); Sb.Append(NewString (b,0, Len)); } input.Close(); System. out.println(sb.)toString());}

You can also use a file object to create an input stream object to read the file. We first have to use the File() method to create a file object:

new File("src/test.txt"new FileInputStream(f);

You must first create a file in the SRC directory test.txt with the content: Hello World
Operation Result:

11hello world
Example 4: Console output:

We know that the output of the console print() is println() done by and. These methods are defined by the class PrintStream and System.out are a reference to the class object.
PrintStreamThe OutputStream class is inherited and the method is implemented write() . This write() can also be used to write to the console.
However write() , the method is not used frequently, because it is print() println() more convenient to use with the method.

PrintStreamThe write() simplest format defined is as follows:

voidwrite(int byteval){}

The method byteval writes a low eight-bit byte to the stream.

publicstaticvoidmain(String[] args) {    System.out.write('h');    System.out.write('\n');}
Example 5: Output content to a file
publicstaticvoidmainthrows IOException{            "hello world";        // 构建FileOutputStream对象,文件不存在会自动新建    new FileOutputStream("src/test2.txt");    out.write(str.getBytes());    out.close();}

You can also use a file object to create an output stream to write a file. We first have to use the File() method to create a file object:

new File("src/test2.txt"new FileOutputStream(f);

After running, open src the eyes, you can see the test2.txt.

getBytes()Used to convert a string into byte stream. Method Prototypes:

publicbytegetBytes() {    return StringCoding.encode0, value.length);}publicbytegetBytes(Charset charset) {    ifnullthrownew NullPointerException();    return StringCoding.encode0, value.length);}
Example 6: Output content to a file with BufferedWriter
publicstaticvoidmainthrows IOException{            "hello";        // 构建FileOutputStream对象,文件不存在会自动新建    new FileOutputStream("src/test3.txt");    new BufferedWriter(new OutputStreamWriter(out));    bWriter.write(str);    bWriter.close();//关闭缓冲区}

We can also combine the above BufferedReader to enter from the keyboard, save to file:

 Public Static void Main(string[] args)throwsioexception{String str ="";//Build FileOutputStream object, file does not exist automatically newOutputStream out =NewFileOutputStream ("Src/test3.txt"); BufferedWriter Bwriter =NewBufferedWriter (NewOutputStreamWriter (out,"Utf-8"));//Build OutputStreamWriter object, parameters can specify encoding, default is operating system default encoding, Windows is GBK//Bwriter.write (str);        //Read bufferBufferedReader br =NewBufferedReader (NewInputStreamReader (System.inch)); Do{str = br.ReadLine(); Bwriter.Write(str); System. out.println(str); } while(!str.equals("Quit")); Bwriter.Close();//close buffer while writing buffer contents to fileOut.Close();//close the output stream and release system resources}
File and I/O

There are mainly these classes:

    • File class.
    • The FileReader FileReader class InputStreamReader inherits from the class. This class reads the data in the stream by character.
    • The FileWriter FileWriter class OutputStreamWriter inherits from the class. This class writes data to the stream by character.

FileClass has at least one parameter. Fileclass Method:

    • mkdir()Method creates a folder, returns True if successful, and returns False if it fails.
      Failure indicates that the path specified by the file object already exists, or that the folder cannot be created because the entire path does not yet exist.
    • mkdirs()Creates the specified directory, including creating a parent directory that is required but does not exist. Use this method to create a multilevel directory.
    • isDirectory()Determine if it is a directory.
    • isFile()Determine if it is a standard file.
    • list()Extracts the list of contained files and folders.
    • delete()Method is the same as deleting files or empty directories.
    • createNewFile() throws IOException
      When and only if a file with the name specified by this abstract pathname does not exist, Atomically creates a new empty file specified by this abstract path name.

Example 1: Directory Operations

 Public Static void Main(string[] args)throwsIOException {String dirname ="Src/tmp"; File File =NewFile (dirname);//Create a directory    if(!file.isdirectory()) {if(file.mkdirs()) {System. out.println("Succ mkdirs"); }    }//Create fileFile file2 =NewFile (dirname +"/test.txt"); File2.CreateNewFile();//directory must existFile File3 =NewFile (dirname +"/test/"); File3.mkdir();//List directory    if(file.isdirectory()) {string[] lists = file.List(); for(inti =0; I < lists.length; i++) {File F =NewFile (dirname +"/"+ lists[i]);if(F.isdirectory()) {System. out.println("[d]"+ lists[i]); }Else{System. out.println("[F]"+ lists[i]); }        }    }Else{System. out.println(DirName +"Not a directory"); }//delete files or directories    if(File3.Delete()) {System. out.println("Delete succeeded"); }}

Operation Result:

[d]test[f]test.txt删除成功

Example 2:

 Public Static void Main(string[] args)throwsIOException {String filename ="Src/tmp/test.txt"; File File =NewFile (filename); File.CreateNewFile();//Create fileFileWriter Fwriter =NewFileWriter (file);//Create FileWriter objectFwriter.Write(' I '); Fwriter.Write(' ');Char[] cs = {' l ', ' o ', ' V ', ' e ', '}; Fwriter.Write(CS); Fwriter.Write("Java"); Fwriter.Flush();//Refreshes the buffers in the input stream and output stream so that the elements in the buffer are instantly input and output, without waiting for the buffer to be fullFwriter.Close();//Close FileWriter object        //Read fileFileReader Freader =NewFileReader (file);Char[] CS2 =New Char[ the]; Freader.Read(CS2);//This is not read by the while loop because it knows the length is not greater than 15     for(CharC:CS2) {//Traversal outputSystem. out.Print(c); } freader.Close();

Operation Result:

i love java
Reference

1. Java Stream (stream), file, and Io | Beginner's Tutorial
Http://www.runoob.com/java/java-files-io.html
2. Conversion of char and Byte in Java-CSDN blog
http://blog.csdn.net/feixiazhitian/article/details/49511963
3. The difference between byte stream and character stream--Jay-Brooks-Blog Park
Https://www.cnblogs.com/sjjsh/p/5269781.html
4, Java, BufferedReader class introduction and Role-CSDN blog
http://blog.csdn.net/wiebin36/article/details/51912794

Java notes: Java stream, file, and IO

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.