Java Learning IO Stream

Source: Internet
Author: User

IO Flow Overview

Before the program, the data is in memory, once the program runs the end, the data will be gone. The appearance of Io stream is to save the data of the operation, the next time you run the program can also use. The storage for persisting data is to store the data in memory to other persistent devices (CD, hard disk, USB stick, etc.) that are not in memory.

when you need to store the in-memory data on a persistent device this action is called output (write) The Output operation.

This action is called input (read) when the data on the persistent device is read into memory Input operation.

so we call this input and output action IO operation.

File class

The file class has two static member variables and three construction methods

1, PathSeparator and system-related path separator;

2. Separator The default name delimiter associated with the system \

Construction method: 1, File (String pathname)

2. File (file parent,string child)

3. File (String parent,string Child)

Package Com.oracle.demo1;import Java.io.file;public class Filedemo {public static void main (string[] args) {//system-related path delimited Identifier String pathseparator = File.pathseparator; System.out.println (PathSeparator);//system-related default name delimiter String separator = file.separator; SYSTEM.OUT.PRINTLN (separator);//construction Method A file (String pathname) file F = new file ("D:\\eclipsework1"); System.out.println (f);//Construction Method two file (file parent,string child) file parent = new file ("D:"); File F2 = new file (parent, "ECLIPSEWORK1"); SYSTEM.OUT.PRINTLN (F2);//Construction Method three file (string parent, String child) file F3 = New file ("D:", "eclipsework1"); System.out.println (F3);}}

Common methods for file classes

1. Create a file

Boolean

CreateNewFile ()

2. Create a folder

Boolean

mkdir () Single-level catalogs

Boolean

Mkdirs () Multilevel directory

3. Delete

Boolean

Delete ()

4. Determine if this file exists

Boolean

Exists ()

5. Determine if this file is a folder

Boolean

Isdirectory ()

6. Get the absolute path

String

GetAbsolutePath ()

7. Get the file name

String

GetName ()

8. Get the path

String

GetPath ()

9. Length

Long

Length ()

package com.oracle.demo1;import java.io.file;import java.io.IOException; public class FileDemo2 {public static void main (string[] args) throws IOException {//Create File//File F = new file ("D:\\eclips E\\demo.java ");//Boolean B = F.createnewfile ();//System.out.println (b);//Create folder with MkDir () (Multilevel directory with mkdirs ())//File F2 = new File ("D:\\eclipse\\test\\test2");//Boolean B = F2.mkdirs ();//System.out.println (b);//delete (deleted file does not go to recycle Bin, delete directly from hard disk)// File F2 = new file ("D:\\eclipse\\test\\test2");//Boolean B = F2.delete ();//System.out.println (b);//determine if path exists//File F = New file ("D:\\eclipse");//Boolean B = f.exists ();//System.out.println (b);//file, directory (folder) directory, Path path//Boolean Isdirectory () Determines whether the file object is a folder//system.out.println (F.isdirectory ());//The file is obtained//absolute path file F=new file ("D:\\eclipsework1" )///relative path file f1=new file ("src"); System.out.println (F.getabsolutepath ()); System.out.println (F.getname ()); System.out.println (F.getpath ()); System.out.println (F.length ());}} 

Listfiles () method

The Listfiles () method is used to get all the files and folders in a directory, resulting in an array or collection

Package Com.oracle.demo1;import Java.io.file;public class Listfiledemo {public static void main (string[] args) {//create you want to get The path object of file F = new file ("D:\\JAVA\\JDK");//Gets an array of files under this path file[] F2 = F.listfiles ();//iterates over the array to get the files for (file file:f2) {System. Out.println (file);} System.out.println (F2.length);}}

Note: The following two conditions must be met when obtaining a file or folder under a specified directory

1, the specified directory must be present,

2, the specified must be a directory. Otherwise, it is easy to raise the return array to null, which appears nullpointerexception

File filter

A file filter is required when we need a specified file in the file. The Listfiles method is overloaded in the file class, and the specified filter is accepted

Package Com.oracle.demo1;import Java.io.file;import Java.io.filefilter;public class Myfilter implements FileFilter{ Public Boolean accept (File pathname) {        String p=pathname.getname (); return P.endswith (". exe");}} Package Com.oracle.demo1;import Java.io.file;public class FileDemo3 {public static void main (string[] args) {File f = new File ("D:\\java\\jdk\\bin"); file[] F2 = f.listfiles (new Myfilter ()); for (File f3:f2) {System.out.println (F3);}}}

Recursive invocation 

Recursion: a phenomenon that invokes itself within the current method

Package Com.oracle.demo2;public class Demo1 {public static void main (string[] args) {//1......N value int sum = getsum (+); S YSTEM.OUT.PRINTLN (sum); System.out.println (Get (5));} Recursive call public static int getsum (int a) {if (a==1) {return 1;} Return a + getsum (A-1);} recursive factorial public static int get (int b) {if (b==1) {return 1;} Return B*get (b-1);}}

  

Note: Recursive must have conditional qualification, to ensure that recursion can stop, or the stack memory overflow will occur.

Although there are qualifications in recursion, the number of recursion cannot be too many. Otherwise, a stack memory overflow will occur.

Exercise: 1, recursively print all files under the specified directory and subdirectories

2. Recursive call to print all. exe files under D:\JAVA\JDK

3. Use the file name filter filter to get and print small files smaller than 200K under the specified folder

package Com.oracle.demo2;import Java.io.file;public class Demo4 {public static void Main (string[] args) {File file = new file ("D:\\java\\jdk"); Getfileall (file);} Gets all files in the specified directory and subdirectories public static void Getfileall (file file) {file[] files = file.listfiles ();//traverse All files and folders in the current directory for ( File f:files) {//To determine whether the current traversal is a directory if (F.isdirectory ()) {///is a directory, continue to get all files and folders under this directory Getfileall (f);} else{//is not a directory, stating that the current F is the file, then print out System.out.println (f);}}} 
package Com.oracle.demo2;import Java.io.file;public class LianXi {public static     void Main (string[] args) {file File=new file ("D:\\java\\jdk"); get (file);}     public static void get (file f) {//Get array of files file[] File2=f.listfiles (New Myfilefilterdemo ());     Traverse all files under the current file for (file f2:file2) {if (F2.isdirectory ()) {get (F2);     }else{System.out.println (F2); }}}}package com.oracle.demo2;import java.io.file;import java.io.filefilter;public class MyFileFilterDemo im Plements Filefilter{public Boolean Accept (File pathname) {if (Pathname.isdirectory ()) {return true;}  String P=pathname.getname (); return P.endswith (". exe");} }
Package Com.oracle.demo2;import Java.io.file;public class Demo01 {public static void main (string[] args) {//1. Using the file name filter sieve Select to get and print small files smaller than 200K under the specified folder. File File = new file ("D:\\java\\jdk");        Get (file);} public static void get (file f) {//Gets the specified path file array file[] File2=f.listfiles (New Myfiledemo ());//traversal gets all files for (file f2:file2) {// If it is a folder, continue to traverse the inside of the file if (F2.isdirectory ()) {get (F2);} ELSE{SYSTEM.OUT.PRINTLN (F2);}}} Package Com.oracle.demo2;import Java.io.file;import Java.io.filefilter;public class Myfiledemo implements FileFilter { Public Boolean accept (File pathname) {if (Pathname.isdirectory ()) {return true;} if (Pathname.length ()/1024<200) {return true;} return false;}}

BYTE stream

Some of the methods of the file class that I learned earlier operate on empty files or folders, and do not write any data into it, and now we are going to write the data through the byte stream to the file.

BYTE output stream OutputStream

OutputStream is an abstract class that represents all the ancestor classes of all the classes that output the byte stream, and the manipulated data are bytes

Common methods: 3 Write () and a close () method

FileOutputStream Subclass of OutputStream class

FileOutputStream for writing data to a file

Construction Method:

FileOutputStream ( File file): Default overwrite file

FileOutputStream (String name): Default Overwrite file

FileOutputStream (String Name,boolean append)

Note: If Appand is true, it means that the file can be continued

If Append is False, it indicates that the overwrite file

Package Com.oracle.demo3;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;public Class Outputstreamdemo {/* * FileOutputStream creates an object, and when the constructor method is called, if your file exists in this file object, then you will be overwritten if it does not exist, creating new * FileOutputStream (f) for you; If the construction method passes a value equivalent to the new FileOutputStream (F,false), will give you a overwrite * if new FileOutputStream (f,true), then the file can be continued to write, do not give you overlay add "\ r \ n" * The unit of the byte stream operation is the bytes write () method, which can only be written to one byte at a Time 100 represents the SACII value inside the D * Stream object using step * 1, create the Stream subclass object, bind data * 2, call the Write () method * 3, close the Stream object, call the Close () method, release the funding SOURCE */public static void main (string[] args) throws IOException {//File F = new File ("D:\\eclipse\\demo.txt");//FileOutput Stream fos = new FileOutputStream (f, true);//fos.write;//Fos.write (+);//Fos.write (48);//If you pass in a negative number, then go kanji// A Chinese character accounts for two bytes, one digit takes up one byte//byte[] b={-12,-23,-30,-45};//byte array Write method//Fos.write (b);/void Write (byte[] B,int off,int len );//Fos.write (b, 1, 2);//requirements: Incoming Hello GetBytes () returns an array of bytes//fos.write ("\r\njava". GetBytes ());//Fos.close ();// Create a java.txtfile f = new File ("E:\\test\\java.txt"); FileoutputstreaM fos = new FileOutputStream (f, true); Fos.write ("Java is the best language in the World". GetBytes ()); Fos.close ();}} 

Operation steps for the output stream:

    1. Creating a Stream object
    2. Call The Write () method: Write only one byte at a time
    3. Close Colse

IO exception Handling

Package Com.oracle.demo3;import Java.io.fileoutputstream;import Java.io.ioexception;public class ThrowsDemo {/* IOException Processing Details * 1, to ensure that the scope of the flow object is sufficient (declared outside the block, in the block Assignment) * 2, catch inside how to deal with exceptions *    IO exception once appeared, generally cannot process *    First: Output exception information; second: throw new RuntimeException * 3, Stream object failed to build, still need to close resources? *    plus a judgment, if (fos!=null) * */public static void Main (string[] args) {FileOutputStream fos = null;try {fos = new FILEOUTPU TStream ("E:\\test\\java.txt"); Fos.write ("Java is the best language in the World". GetBytes ()); catch (IOException e) {e.printstacktrace (); throw new RuntimeException ("File write failed, retry");} finally {try {if (fos! = null) {fos. Close ();}} catch (IOException e) {e.printstacktrace ();}}}}

BYTE input stream InputStream

InputStream This abstract class , which is the ancestor class for all classes that represent the byte input stream . , the basic common function method of byte input stream is defined.

int read (): reads a byte and returns, no bytes returned-1.

int read (byte[]): reads a certain amount of bytes and stores it in a byte array, returning the number of bytes read to

FileInputStream Subclass of InputStream class

Construction Method:

Input stream Operation steps:

    1. Creating a Stream object
    2. Read ()
    3. Close ()
Package Com.oracle.demo3;import Java.io.fileinputstream;import Java.io.ioexception;public class InputStreamDemo {  public static void Main (string[] args) {FileInputStream fis = null;try {fis = new FileInputStream ("E:\\test\\java.txt");// The read () method can read only one byte at a time, and returns 1 if the end of the stream is reached. int b = Fis.read ();//byte[] b = new byte[100];//int c = fis.read (b);//For (byte b1:b) {//System.out.println (B1); /}//System.out.println (c);//1, Readint len = 0;while (len = Fis.read ())! =-1) {System.out.print ((char) len);}  2, read (byte[] b) byte[] b = new Byte[1024];int L = 0;while ((L=fis.read ())!=-1) System.out.println (new String (b, 0, L));} catch (IOException ex) {ex.printstacktrace (); throw new RuntimeException ("file read failed, retry");} finally {try {fis.close ()} catch (IOException ex) {ex.printstacktrace ();}}}}

  

Java Learning IO 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.