Dark Horse programmer--java Basic---IO (bottom)

Source: Internet
Author: User
Tags list of attributes

Dark Horse programmer--java Basic---IO (bottom)

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! ------

I. Overview

In addition to the basic byte stream and character stream, Java provides classes such as the file class, properties class, print stream, sequence flow and input and output, which can help us to better handle the information. They are briefly described below.

 

First, the text

1 , File class

the file class is an object that encapsulates files and folders in the file system, and can manipulate files and folders through the idea of an object. It is characterized by: used to encapsulate files or folders into objects, easy to manipulate the properties of files and folders, the instance of the file class is immutable, that is, once created, the name of the abstract path represented by the file object will never change; A file object can be passed as a parameter to the stream constructor

By invoking the various methods of the file class, it is possible to create a file, delete a file, rename a file, determine the file's Read permission and whether the file exists, set and query the last modified time of the file, and so on. It is commonly used in the following ways:

1. Created: Boolean createnewfile ();//creates a file at the specified location, if the file already exists, is not created, and returns false. Unlike the output stream, it will overwrite if the file already exists. boolean mkdir ();//Create a folder, you can create only one level folder2. Delete: Boolean delete ();//deletes a file or directory. The file exists, returns True, the file does not exist or is being executed, and returns false.       voidDeleteonexit ();//Delete the specified file when the program exits3. Judge: Boolean CanExecute ();//whether it is an executable fileBoolean exists ();//whether the file existsboolean isfile ();//whether it is a fileboolean isdirectory ();//whether it is a folderboolean Ishidden ();//is a hidden fileboolean Isabsolute ();//whether the file is an absolute path

Here is a piece of code: If a directory is given, all the files in this directory are required to be listed, including files under subfolders.

 Public classTest8 { Public Static voidMain (string[] args) {File F=NewFile ("D:"+file.separator);       Print (f);}  Public Static voidprint (File f) {if(F! =NULL) {              if(F.isdirectory ()) {file[] files=F.listfiles (); if(Files! =NULL) {               for(file file:files) {print (file); }              }}     Else{System. out. println (f); } }}}

  Note: The file class is the only one in the java.io package that is related to the files themselves, and can be used to create, delete, and so on common file operations. When you use the file class to specify a path, be aware of the differences between operating systems and use separator to split them as much as possible.

2 , Properties class

Properties is a subclass of Hashtable, which has the characteristics of a map collection. And it has stored key-value pairs, all strings, no generic definitions. Is the collection container that the collection and IO technologies want to combine. A configuration file that can be used in the form of a key-value pair, which requires a fixed format of data at load time, usually: key = value

Here's how it's used:

1. Constructor properties ()//creates a list of empty properties with no default values. 2. String GetProperty (String key)//gets the key value of the specified key key, returned as a string. 3. voidLoad (inputstring instream)//reads the list of attributes from the input stream. 4. voidSetProperty (string key, String value)//sets the key value of the key in the object. 5. VoidStore (OutputStream OutStream, String comments)//writes Putstream according to comments. 6. VoidList (PrintStream out)//outputs a list of attributes to the specified output stream. 7. Set<string> Stringpropertyname ()//returns the set of keys for the property list, stored in the Set collection

The following program demonstrates the use of the properties class common methods:

 Public classPropertiessample { Public Static voidMain (String args[]) throws Exception {//create an empty parameter objectProperties prop=NewProperties (); //Create a byte input stream objectFileInputStream fis=NewFileInputStream ("sample1.properties");            Prop.load (FIS); Prop.list (System. out); String Foo= Prop.getproperty ("Foo"); String Fu= Prop.getproperty ("Fu"); System. out. println ("foo ="+foo); System. out. println ("fu ="+fu); FileOutputStream Fos=NewFileOutputStream ("sample1.properties"); Prop.setproperty ("Foo","FooValue55"); Prop.setproperty ("Fu","FuValue55"); Prop.put ("Testkey1","TestValue"); Prop.store (FOS,"Store properties to Sample1.properties"); FileInputStream Fis1=NewFileInputStream ("sample1.properties");            Prop.load (FIS1); Prop.list (System. out); }   }

3 , print flow

in the entire IO package, the print stream is the most convenient class for outputting information, mainly containing the byte print stream (PrintStream) and the character print stream (PrintWriter). The print stream provides a very convenient printing function that can print any data type. For example: decimals, integers, strings, and so on.

BYTE print stream PrintStream the type of parameter that can be received in the construction method: The File object, the string path, string, and the character output outputstream.

The string print stream PrintWriter the acceptable parameter types in the constructor method: file object, String path strings, byte output stream outputstream, and character output stream writer.

Here's a sample code: typing data through the keyboard, printing to the console, requires the use of a print stream.

 Public classPrintstreamdemo { Public Static voidMain (string[] args) throws IOException {BufferedReader Bufr=NewBufferedReader (NewInputStreamReader (System.inch)); //The parameter true indicates whether automatic Flush,true is automaticallyPrintWriter PW=NewPrintWriter (NewFileWriter ("Haha.txt"),true); String Line=NULL;  while((Line=bufr.readline ())! =NULL)         {             if(" Over". Equals (line)) Break; //Pw.write (Line.touppercase ());//Cannot break line//can use println, can wrap, and newline is BufferedWriter methodpw.println (Line.touppercase ());         } bufr.close ();     Pw.close (); } } 

4 , Sequence Flow

Sequenceinputstream to merge multiple streams. Also known as the merge stream. Common steps to merge multiple stream files:

    1. Creates a vector collection and adds a Stream object into the collection
    2. Creates a enumeration object with the vector's elements () and joins the collection element.
    3. Creating Sequenceinputstream objects, merging stream objects
    4. Create write stream FileOutputStream Object Association write file
    5. Use Sequenceinputstream objects and FileOutputStream object read data for repeated read and write operations.

Here's a sample code: merge three files into one file.

classSequenceinputstreamdemo { Public Static voidMain (string[] args) throws IOException {//Create a vector collection and add related flow objectsVector<InputStream> vector =NewVector<inputstream>(); Vector.add (NewFileInputStream ("Book1.txt")); Vector.add (NewFileInputStream ("Book2.txt")); Vector.add (NewFileInputStream ("Book3.txt")); //creating an Enumeration objectEnumeration<InputStream> en =vector.elements (); Sequenceinputstream SIS=Newsequenceinputstream (en); FileOutputStream Fos=NewFileOutputStream ("Book4.txt"); //Read and write operations     byte[] by=New byte[1024x768]; intlen=0;  while(Len=sis.read (by))!=-1) {Fos.write (by,0, Len); }
//Close Stream ObjectSis.close (); Fos.close (); } }

Third, Summary

This article describes the ability to manipulate files and folders of the file class, as well as the ability to print any data of the print stream, as well as the operation key value of the configuration file properties class, and finally described the ability to merge multiple streams of Sequenceinputstream, we hope to help.

Dark Horse programmer--java Basic---IO (bottom)

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.