Files and streams

Source: Internet
Author: User
Tags file copy


Files and streams
Lingwen20 sorting and updating: 03:50:46 version: 1.0

Files and streams
There are too many classes for Java I/O systems. Here we only learn some basic and common classes. I believe that mastering these classes will solve our common applications in the future.

1. What is data stream?
Data Flow refers to all data communication channels
There are two types of streams: inputstream and outputstream. The basic functions of each stream in Java depend on them.
Inputstream is used for read, and outputstream is used for write. Reading and writing are relative to memory. Reading is to take data into memory from other places, and writing is to push data out of memory.
Both are abstract classes and cannot be used directly.
2. inputstream methods include:
There are three methods to read data from a stream:
Int read () reads one byte at a time
Int read (byte []) reads multiple bytes to the array
Int read (byte [], int off, int Len) specifies where the array starts and how long it reads
Several bytes in the skip () Hop over-current
Available () returns the number of available bytes in the stream, but is invalid when the network is based. 0 is returned.
Marksupported () determines whether tag and reset operations are supported
Mark () marks a position in the stream and must be used with marksupported ()
Reset () returns the marked position
Close () Close the stream
3. Method of outputstream:
Write (INT) writes a byte to the stream.
Write (byte []) writes the content in the array to the stream
Write (byte [], int off, int Len) writes the LEN Length data from the position specified by off to the stream.
Close () Close the stream
Flush () Forcibly outputs data in the buffer zone
4. File class
File can indicate a file or a directory, and the file class controls all hard disk operations.
Constructor:
File (File parent, string child) is constructed using the parent class and file name
File (string pathname) is constructed using an absolute path
File (string parent, string child) is constructed using the parent directory and file name
File (URI) is constructed using a Remote File
Common Methods:
Boolean createnewfile ();
Boolean exists ();

Example:
// Create a test.txt object to check whether the object exists.
Import java. Io .*;

Public class createnewfile {
Public static void main (string ARGs []) {
File F = new file ("test.txt ");
Try {
If (! F. exists ())
F. createnewfile ();
Else
System. Out. println ("exists ");
} Catch (exception e ){
E. printstacktrace ();
}
}
}

Boolean mkdir ()/mkdirs ()
Boolean renameto (file destination)
Example: // check the difference between mkdir ()/mkdirs () and renameto usage.
Import java. Io .*;
Public class createdir {
Public static void main (string ARGs []) {
File F = new file ("test.txt ");
File F1 = new file ("dir ");
File F2 = new file ("Top/bottom ");
File F3 = new file ("newtest.txt ");
Try {
F. renameto (F3 );
F1.mkdir ();
F2.mkdirs ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}

String getpath ()/getabsolutepath ()
String getparent ()/getname ()
Example: // there is no parent directory or test.txt file on the hard disk, but we can still operate it because we have created their objects and operated on them.
Import java. Io .*;
Public class test {
Public static void main (string ARGs []) {
File F = new file ("Parent/test.txt ");
File F1 = new file ("newtest.txt ");
Try {
System. Out. println (F. getparent ());
System. Out. println (F. getname ());
System. Out. println (f1.getpath ());
System. Out. println (f1.getabsolutepath ());
} Catch (exception e ){
E. printstacktrace ();
}
}
}

String list [] // display all files in the directory
Long lastmodified () // returns the number of seconds from 1970.1.1 to the last modification time
Boolean isdirectory ()
Example: // list all files and directories in the directory. The last modification time is <dir> marked after the directory, and the file length marked after the file.
Import java. Io .*;
Import java. util .*;
Public class dir {
Public static void main (string ARGs []) {
File F = new file ("dir ");
String [] listall = NULL;
File temp = NULL;
Try {
Listall = f. List ();
For (INT I = 0; I <listall. length; I ++ ){
Temp = new file (listall <I> );
System. Out. Print (listall <I> + "/t ");
If (temp. isdirectory ())
System. Out. Print ("/T <dir>/t ");
Else
System. Out. Print (temp. Length () + "/t ");
System. Out. println (new date (temp. lastmodified ()));
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}

5. Create a file stream
File F = new file ("temp.txt ");
Fileinputstream in = new fileinputstream (f );
Fileoutputstream out = new fileoutputstream (f );

Example: copy a file
Import java. Io .*;
Public class copy {
Public static void main (string ARGs []) {
Fileinputstream FCM = NULL;
Fileoutputstream Fos = NULL;
Try {
FCM = new fileinputstream ("c2.gif ");
Fos = new fileoutputstream ("c2_copy.gif ");
Int C;
While (C = FCM. Read ())! =-1)
FOS. Write (C );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (FS! = NULL) Try {fs. Close ();} catch (exception e) {e. printstacktrace ();}
If (FOS! = NULL) Try {FOS. Close ();} catch (exception e) {e. printstacktrace ();}
}
}
}

6. Buffer stream
Bufferedinputstream
Bufferedoutputstream
They added the buffer function to the normal file stream, so they must first construct the normal stream when constructing them.
Example: file copy buffer Improvement

Import java. Io .*;
Public class copy {
Public static void main (string ARGs []) {
Bufferedinputstream Bis = NULL;
Bufferedoutputstream Bos = NULL;
Byte Buf [] = new byte [100];
Try {
Bis = new bufferedinputstream (New fileinputstream ("persia.mp3 "));
Bos = new bufferedoutputstream (New fileoutputstream ("persia_copystream "));
Int Len = 0;
While (true ){
Len = bis. Read (BUF );
If (LEN <= 0) break;
Bos. Write (BUF, 0, Len );
}
Bos. Flush (); // data is output to the output stream only when the buffer is full. Use flush () to forcibly output data in the buffer that is not full.
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (Bis! = NULL) Try {bis. Close ();} catch (exception e) {e. printstacktrace ();}
If (Bos! = NULL) Try {Bos. Close ();} catch (exception e) {e. printstacktrace ();}
}
}
}

7. Original data stream
Datainputstream
Dataoutputstream
They added the ability to read and write the original data to a common stream. Therefore, when constructing them, you must first construct a common stream.
Method:
Readboolean ()/writeboolean ()
Readbyte ()/writebyte ()
Readchar ()/writebyte ()
......

Example: // this stream is relatively simple. Note that the reading sequence must be the same as the writing sequence.
Import java. Io .*;
Public class dataout {
Public static void main (string ARGs []) {
Dataoutputstream dos = NULL;
Try {
DOS = new dataoutputstream (New fileoutputstream ("dataout.txt "));
Dos. writeint (1 );
Dos. writeboolean (true );
Dos. writelong (100l );
Dos. writechar ('A ');
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (dos! = NULL)
Try {
Dos. Close ();
} Catch (exception e ){
}
}
}
}

Import java. Io .*;
Public class dataIn {
Public static void main (string ARGs []) {
Datainputstream Dis = NULL;
Try {
Dis = new datainputstream (New fileinputstream ("dataout.txt "));
System. Out. println (DIS. readint ());
System. Out. println (DIS. readboolean ());
System. Out. println (DIS. readlong ());
System. Out. println (DIS. readchar ());
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (DIS! = NULL)
Try {
Dis. Close ();
} Catch (exception e ){
}
}
}
}

8. Object stream
Serialization: an object describes its own process by writing a number describing its own State.
Object stream: stream that can input and output objects
Write serialized objects into files or transmit them to other places through object streams
Object stream adds the object transfer function to a normal stream. Therefore, when constructing an object stream, you must first construct a normal file stream.
Note: Only classes that implement the serializable interface can be serialized.
Example:
Import java. Io .*;
Class student implements serializable {
Private string name;
Private int age;

Public student (string name, int age ){
This. Name = Name;
This. Age = age;
}

Public void greeting (){
System. Out. println ("Hello, my name is" + name );
}

Public String tostring (){
Return "student [" + name + "," + age + "]";
}
}
Public class objectouttest {
Public static void main (string ARGs []) {
Objectoutputstream OOS = NULL;
Try {
Oos = new objectoutputstream (
New fileoutputstream ("student.txt "));
Student S1 = new student ("Jerry", 24 );
Student S2 = new student ("Andy", 33 );

Oos. writeobject (S1 );
Oos. writeobject (S2 );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (OOS! = NULL)
Try {
Oos. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
}

Import java. Io .*;
Public class objectintest {
Public static void main (string ARGs []) {
Objectinputstream OIS = NULL;
Student s = NULL;
Try {
Ois = new objectinputstream (
New fileinputstream ("student.txt "));
System. Out. println ("--------------------");
S = (student) Ois. readobject ();
System. Out. println (s );
S. Greeting ();
System. Out. println ("--------------------");
S = (student) Ois. readobject ();
System. Out. println (s );
S. Greeting ();
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (OIS! = NULL)
Try {
Ois. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
}

9. inputstreamreader/outputstreamwriter
The units of the above streams are byte. Therefore, byte streams are used to write binary bytes to files. We cannot directly look at them. What we need to learn below is byte streams.
Java uses the Unicode Character Set. Each character and Chinese character are encoded in two bytes. the ASCII code is the Unicode-encoded self-set.
Inputstreamreader is a bridge between byte streams and character bridges (byte-> char reads bytes and then encodes them into characters using a specific character set)
Outputstreamwriter is a bridge between bytes stream and byte stream (char-> byte)
They are based on byte streams, so when constructing them, you must first construct a normal file stream.
We often use:
Bufferedreader method: Readline ()
Printwriter method: println ()

Example:
Import java. Io .*;
Public class printwritertest {
Public static void main (string ARGs []) {
Printwriter PW = NULL;
Try {
PW = new printwriter (
New outputstreamwriter (
New fileoutputstream ("bufferedwriter.txt ")));
PW. println ("Hello World ");
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (PW! = NULL)
Try {
PW. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
}

Import java. Io .*;
Public class bufferedreadertest {
Public static void main (string ARGs []) {
Bufferedreader BR = NULL;
Try {
BR = new bufferedreader (
New inputstreamreader (
New fileinputstream ("bufferedwriter.txt ")));
System. Out. println (Br. Readline ());
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (BR! = NULL)
Try {
BR. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
}

10. Random Access File randomaccessfile
Read/write operations can be completed at the same time
Methods that support random file operations:
Readxxx ()/writexxx ()
Seek () adjusts the pointer to the desired position
Getfilepointer () returns the current pointer position
Length () returns the object length.
Example: write several 32-bit Integers to a file named “temp.txt, and then read the data in reverse order using the seek method.
Import java. Io .*;
Public class randomfile {
Public static void main (string ARGs []) {
Randomaccessfile RAF = NULL;
Int data [] = };
Try {
RAF = new randomaccessfile ("temp.txt", "RW ");
For (INT I = 0; I <data. length; I ++)
Raf. writeint (Data <I> );
For (INT I = data. Length-1; I> = 0; I --){
Raf. Seek (I * 4 );
System. Out. println (RAF. readint ());
}
} Catch (exception e ){
E. getmessage ();
} Finally {
If (RAF! = NULL)
Try {
Raf. Close ();
} Catch (exception e ){
E. getmessage ();
}
}
}
}

 

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.