Java basic knowledge IO (1)

Source: Internet
Author: User
Tags throw exception

Main classes and interfaces in IO

File, InputStream, OutputStream, Reader, Writer, serialzable interface

File class

Small examples of file class applications

Import Java.io.file;import java.io.IOException; Public classFiledemo { Public Static void Main(string[] args) {//Specify file path and nameString Path ="D:"+file.separator+"1.txt";//Instantiation File classFile File =NewFile (path);//Determine if the path isSystem. out. println ("is path:"+file.isdirectory ());//Determine if the file exists        if(File.exists ()) {System. out. println ("file exists!"); File.delete ();//delete files}Else{System. out. println ("The file does not exist, but it has been created ... ");Try{File.createnewfile ();//Create file, may throw exception}Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }    }}

Lists all folders in a specified directory, and folders inside folders

Import Java.io.File; Public classFileDemo2 {Private StaticFile F;Private StaticFile[] FS; Public Static void Main(string[] args) {String Path ="D:"+file.separator+"android.7z";//Specify directoryFun (path);//List all subdirectories under this directory, and subdirectory contents} Public Static void  Fun(String s) {f =NewFile (s);//Instantiation of the file class        if(F.isdirectory ()) {//Determine if the path isFS = F.listfiles ();//List             for(File T:fs) {System. out. println (t);if(T.isdirectory ())                {Fun (t.tostring ()); }            }        }Else{System. out. println (f); }    }}

The file class can operate on only one of the files themselves, and if you want to manipulate the contents of the file, you need the Randomaccessfile class

Randomaccessfile

Using the Randomaccessfile class for file read and write operations

ImportJava.io.File;ImportJava.io.IOException;ImportJava.io.RandomAccessFile; Public  class Demo2 {     Public Static void Main(string[] args)throwsIOException {Write ("Demo file read and write operation here","D:"+file.separator+"1.txt"); System.out.println (Read ("D:"+file.separator+"1.txt")); }//content is written to the file, overwriting the original content from the beginning     Public Static void Write(String s,string Path)throwsioexception{File File =NewFile (path);//Instantiate the Randomaccessfile instance, specifying the operation mode as read-write mode, in which case the file does not exist, it is automatically createdRandomaccessfile Rfile =NewRandomaccessfile (file,"RW"); Rfile.write (S.getbytes ());//write in byte formRfile.close (); }//read out the contents of the file     Public StaticStringRead(String Path)throwsioexception{File File =NewFile (path);//Instantiate the Randomaccessfile instance, specifying the operation mode as read-write mode, in which case the file does not exist, it is automatically createdRandomaccessfile Rfile =NewRandomaccessfile (file,"R");intLen = (int) File.length ();//Get the size of the file in bytes        byte[] ss =New byte[Len];//Declare byte array size according to file size         for(intI=0; i<len;i++) {//loop-read every byteSs[i]=rfile.readbyte (); } rfile.close ();//Call the construction of the string class to generate a new string        return NewString (ss); }}
Byte Stream and character stream

1. Byte stream
OutputStream class for output of bytes
InputStream class for byte read-in
2. Character Stream
Writer class for character output
Reader class for character read-in
Here the output, read in is relative to all of us write the program, in the program to write the data out of the program, called output, on the contrary, from outside the program to get the data for the program to use, called Read in;
Before the demo, the basic steps of the IO operation in Java are regulated:
1. Use the file class to find a document
2. Instantiate OutputStream, InputStream, Writer, reader by using byte stream or character stream subclass
3. Read and write operation
4. Close the stream

OutputStream

Output Data instance

ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.OutputStream; Public  class fileoutputstreamdemo {     Public Static void Main(string[] args)throwsIOException {//file path to ensure that the path existsString Path ="E:"+file.separator+"Javaio"+file.separator+"FileOutputStream.txt";//Use the file class to find filesFile File =NewFile (path);//instantiation of the OutputStream classOutputStream out =NewFileOutputStream (file,true);//Join parameter True indicates that content can be appended after the contents of the file        //output operation, when writing data to a file, \ r \ n indicates line breakOut.write (("\ r \ n"+"This is FileOutputStream demo instance"). GetBytes ());//Close streamOut.close (); }}
InputStream

Read in data instance

Import Java.io.file;import java.io.fileinputstream;import java.io.ioexception;import java.io.InputStream; Public classFileinputstreamdemo { Public Static void Main(string[] args) throws IOException {//file pathString Path ="E:"+file.separator+"Javaio"+file.separator+"FileOutputStream.txt";//instantiation fileFile File =NewFile (path);//instantiation of InputStreamInputStreaminch=NewFileInputStream (file);//Read in data        intLen = (int) File.length ();//number of bytes in the file        byte[] bytes =New byte[Len];//Storage space        inch. Read (bytes);//Get DataSystem. out. println (NewString (bytes));//Output        //Close stream        inch. Close (); }}
Writer

Output Data instance

ImportJava.io.File;ImportJava.io.FileWriter;ImportJava.io.IOException;ImportJava.io.Writer; Public  class filewriterdemo {     Public Static void Main(string[] args)throwsIOException {//file pathString Path ="E:"+file.separator+"Javaio"+file.separator+"FileWriter.txt";//instantiation fileFile File =NewFile (path);//Instantiate writer class objectWriter writer =NewFileWriter (file,true);//Output dataWriter.write ("This is FileWriter demo instance"+"\ r \ n");//Close streamWriter.close (); }}
Reader

Read in data instance

ImportJava.io.File;ImportJava.io.FileReader;ImportJava.io.IOException;ImportJava.io.Reader; Public  class filereaderdemo {     Public Static void Main(string[] args)throwsIOException {//file pathString Path ="E:"+ File.separator +"Javaio"+ file.separator+"FileWriter.txt";//instantiation fileFile File =NewFile (path);//instantiation of Reader instanceReader r =NewFileReader (file);//Read in data        intLen = (int) File.length ();//File size        Char[] Cbuf =New Char[Len];//Storage spaceLen = R.read (CBUF);//Read in data, return data lengthSystem.out.println (len); System.out.println (NewString (Cbuf,0, Len));//Close streamR.close (); }}

Explain the difference between OutputStream and writer:
OutputStream in the operation of the file, the byte content is directly written to the file, and writer will write the characters into the buffer, and then write to the file, if the above writer's example of "stream close" action is removed, you can find that there is no content in the file. In fact, the data stored inside the computer is in the form of bytes, so the personal sense of the byte stream can take care of all data forms.

All right, let's get here today ...

Java basic knowledge IO (1)

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.