Java IO

xiaoxiao2021-03-06  85

Java I / O

(Steven Shi, Idealist@gcn.net.tw, 2002/3/31)

ABSTRACT:

Java is divided into high-order I / O and low-order I / O, high-order I / O, providing more read and write methods, such as reading writing int, double, string data, and low-order Most of the I / O only provide Write, Read [] Acquisition, because the large-scale data is calculated in strings or other main types, so low-order I / O is unfavorable in use. For execution design, Java will collect all the best ways to high-end I / O; in other words, the main task of low-order I / O is responsible for accessing the media data, high-order I / O category main data type Conversion and provide some special features. An important principle that you want to keep in mind when using Java I / O, you must use the low-order I / O category before establishing an I / O category, then use the high-order I / O To control the motion of the low-order I / O category, this layer of architecture is called I / O CHAIN.

At the bottom of Java I / O architectural diagram, the first is I / O in Byte, and the second is in units of char.

2. File I / O:

A. FileInputStream & FileOutputStream

FileInputStream is a category for reading files, and its constructive is three:

Public FileInputStream (String Strfilename) Throws FilenotFoundException

Public FileInputStream (File Fin) Throws FilenotFoundException

Public FileInputStream (FileDescriptor FDOBJ)

Here I only say the first one, this is the most intuitive way, as follows 1, will read 10 bytes from E: / Test.txt, output the result of the read, until the file ends. In this example, it is to be noted that how many bytes in the input stream will pass back in the input stream, and read will determine a few Bytes in accordance with the size of the buffer and pass the actually read the BYTE number.

===== Example 1 =====

Import java.io. *;

Public class fin {

Public fin () {

Try {

FileInputStream Fis = New FileInputStream ("e: /in.txt");

While (fis.available ()> 0) {

Byte [] b = new byte [10];

INT NRESULT = Fis.Read (b);

IF (nresult == -1) Break;

System.out.println (New String (b));

}

fis.close ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

FIN FIN = New FIN ();

}

}

FileOutputStream is a category for writing files, and its constructive has four:

Public FileOutputStream (String Strfilename) Throws FilenotFoundException

Public FileOutputStream (File Fout) THROWS Filenotfound Exception

Public FileOutputStream (FileDescriptor fdobj) Public FileoutputStream (String Name, Boolean Append) throws filenotfoundexception

The difference between the fourth and the first one is only that when the file exists, the first one will cover the original file content, and the fourth can select override or connect the new content behind the original content. Example 2 How to write a file in this example ... In this example, FIN read 10 Bytes, but the last time does not necessarily read 10 Bytes, so fouts are in Write, indicate To write a few Bytes to the file, 10 Bytes will still be written in the last time. Because Java will first fill in 0, so several bytes will be 0.

===== Example 2 =====

Import java.io. *;

Public class fout {

Public fout () {

Try {

FileInputStream Fin = New FileInputStream ("e: /in.txt");

FileOutputStream Fout = New FileOutputStream ("E: /out.txt");

While (Fin.available ()> 0) {

Byte [] b = new byte [10];

INT NRESULT = Fin.Read (b);

IF (nresult == -1) Break;

Fout.write (B, 0, NRESULT);

}

Fin.close ();

Fout.close ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

Fout fout1 = new fout ();

}

}

B. FileReader & FileWriter

FileReader and FileInputStream are the largest different that the unit read by FileInputStream is byte, and the unit read by FileReader is char. Also note that in FileInputStream to determine if there is also information to read, in FileReader, it is judged in Ready.

However, Available is over how many bytes can read, ready returns TRUE or FALSE, indicating that when returning TRUE, the next read is not paused, when returned to false, indicates next time read "May" pause, the so-called may not be guaranteed to stop.

Ps. When testing, in In.txt can see what is different from Byte and CHAR units.

===== Example 3 =====

Import java.io. *;

Public class chfin {

Public chfin () {

Try {

FileReader rdfile = new fileReader ("e: /in.txt");

While (rdfile.ready ()) {

CHAR [] chin = new char [10];

INT NRESULT = RDFile.read (chin);

IF (nresult == -1) Break; System.out.Println (China);

}

Rdfile.close ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

CHFIN CHFIN1 = New CHFIN ();

}

}

FileWriter and FileOutststream are also different from the write unit, fileoutputstream is Byte, FileWrit carr for char.

===== Example 4 =====

Import java.io. *;

Public class chfout {

Public chfout () {

Try {

FileReader rdfile = new fileReader ("e: /in.txt");

FileWriter WRFILE = New FileWriter ("e: /out.txt");

While (rdfile.ready ()) {

CHAR [] chin = new char [10];

INT NRESULT = RDFile.read (chin);

IF (nresult == -1) Break;

WRFILE.WRITE (CHIN, 0, NRESULT);

}

Rdfile.close ();

WRFILE.CLOSE ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

Chfout chfout1 = new chfout ();

}

}

C. BufferedReader & bufferedWriter

File I / O is a considerable time-consuming job, usually when the computer is working, build a buffer, read or write a block, saving time, in Java BufferedReader and BufferedWriter provide such a buffer feature.

In Example 5, we guide the FileReader to bufferedReader, direct the FileWriter to BUFFEREDWriter, to reach the block read, write it. The readline provided by BufferedReader can read a line at a time. When you encounter the end, you will pass back NULL. The newline provided by BufferedWriter generates a column symbol. This column symbol is different from the operating system. On Windows / R / N, in Unix / n, in the MAC / R, this symbol is based on Line The .separator system nature comes. It should be noted that if you apply BufferedWriter to a network program, NeWLINE is absolutely don't use NEWLINE because most of the network protocols are tailing with / r / n, and will not vary depending on the job system.

===== Example 5 =====

Import java.io. *;

Public class bufin {

Public bufin () {

Try {

FileReader rdfile = new fileReader ("e: /in.txt");

BufferedReader BrdFile = New BufferedReader (RDFILE); FileWriter WRFILE = New FileWriter ("E: /out.txt");

Bufferedwriter BWRFILE = New BufferedWriter (WRFILE);

String strline;

While (Strline = brdfile.readline ())! = null) {

BWRFILE.WRITE (STRLINE);

BWRFILE.NEWLINE ();

}

Brdfile.close ();

BWRFILE.CLOSE ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

BUFIN bufin1 = new bufin ();

}

}

D. File

In terms of file processing, the program is not just to read, write, sometimes you need to know the properties of the file, or delete, move, rename, sometimes you want to find or list some of the files in a directory. For these operations, Java provides this category. Examples under the bottom show how to use the File category.

a. How to recognize the file properties:

In paragrade 6, it is necessary to note that the last change time of LastModified transmission is from 1970/1/1 00:00:00, the unit is in milliseconds, so use Date to convert it to date, time; additional GetcanonicalPath The value obtained with GetabsolutePath will be the same on Windows, which may be different in UNIX.

===== Example 6 =====

Import java.io. *;

Import java.util. *;

PUBLIC CLASS FILESPY {

Public filespy (String strfilename) {

File ffile = new file (strfilename);

IF (ffile.exists ()) {

System.out.println ("Name:" ffile.getname ());

System.out.println ("Absolute Path:" ffile.getabsolutePath ());

Try {

System.out.println ("Canonical Path:" ffile.getcanonicalPath ());

}

Catch (IOException E) {

E.PrintStackTrace ();

}

IF (ffile.canwrite ()) system.out.println (ffile.getname () "is wh");

IF (ffile.canread ()) system.out.println (ffile.getname () "is ready");

IF (ffile.isfile ()) {

System.out.println (ffile.getname () "is a file");

}

Else if (ffile.isdirectory ()) {

System.out.println (ffile.getname () "is a directory");

}

Else {

System.out.println ("what is this?");

Long LNGMILLISECONDS = ffile.lastmodified ();

IF (LNGMilliseConds! = 0) System.out.Println ("Last Modified AT" New Date (LNGMilliseConds));

Long lnglen = ffile.length ();

IF (LNGLEN! = 0) System.out.println ("Size:" LNGLEN);

}

Else

System.out.println ("File Not Found");

}

Public static void main (String [] args) {

IF (args.length == 1) {

FILESPY FILESPY1 = New FileSpy (args [0]);

}

Else

System.out.println ("USAGE: JAVA FilesPY FileName);

}

}

B. Creating, deleting, moving, rename:

The FILE category provides CreateNewWFile, renameto, delete as a cretenewfile, delete, mobile, renameto, is as follows: (Mobile and renovation with renameto, as file movement and renovation) on UNIX Using MV)

===== Example 7 =====

Import java.io. *;

Public class operatefile {

Public OperateFile () {

// CREATE New File

FILE FNEWFILE = New File ("c: /newfile.txt");

Try {

IF (fnewfile.exists () == false) {

IF (fnewfile.createnewfile () == true) {

System.out.println ("CREATE C: /NEWFILE.TXT SUCCESS");

}

Else {

System.out.println ("CREATE C: /NEWFILE.TXT FAIL");

}

}

Else {

System.out.println ("File Already EXISTS");

}

}

Catch (IOException E) {

E.PrintStackTrace ();

}

// rename file

File FrenameFile = New File ("c: / rMefile.txt");

Fnewfile.renameto (FRENAMEFILE);

// Remove file

File Fremovefile = New File ("D: /" FRenameFile.getName ());

Frenamefile.renameto (FremoveFile);

// delete file

Try {

File fdelfile = new file (freetfile.getcanonicalPath ());

FDELFILE.DELETE ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

OperateFile Operatefile1 = New OperateFile ();

}

c. Find all the files in a certain directory:

The List and ListFiles provided by the FILE category can list all files in a certain directory, where list is String [], Listfiles is file [], these two functions will pass all files and table of Contents.

===== Example 8 =====

Import java.io. *;

Public class listallfiles {

Public ListAllFiles (String strdir) {

FILE FDIR = New File (strdir);

File [] FallFiles = fdir.listfiles ();

For (int i = 0; i

IF (FallFiles [i] .isfile ())

System.out.println ("File:" FallFiles [i] .GetName ());

Else

System.out.println ("DIR:" FallFiles [i] .Getname ());

}

}

Public static void main (String [] args) {

ListAllfiles ListAllFiles1 = New ListAllFiles (Args [0]);

}

}

3. Network I / O:

Java supports only TCP / IP and UDP / IP, and the categories provided include URL, URLCONNECTION, SOCKET, ServerSocket, I only plan to use Serversocket, Socket as an example to illustrate NetWork I / O.

Basically, Java's I / O is regarded as Stream in any media, so network I / O and file I / O principles are also consistent, and the two programs underground are Server Socket and Client, respectively. Socket. Before you look at the example, you can review the ABSTRACT ...

===== Example 9 =====

Import java.net. *;

Import java.io. *;

PUBLIC CLASS MyServer {

Public myserver (string strong) {

INT NPORT = New Integer (Strport) .intValue ();

Try {

Serversocket SS = New ServerSocket (NPORT);

Socket s = ss.accept ();

OutputStream out = s.getoutputstream ();

PRINTSTREAM PSOUT = New PrintStream (OUT);

String strresponse = "Hello" S.GetinetDRESS () "on port" s.getport () "/ r / n";

Strresponse = "this is" s.getlocaladdress () "on port" s.getlocalport () "/ r / n";

PSout.print (strretponse); s.close ();

ss.close ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

MyServer myserver1 = new myserver (args [0]);

}

}

===== Example 10 =====

Import java.net. *;

Import java.io. *;

Public class myclient {

Public myclient (string strip, string strong) {

INT NPORT = New Integer (Strport) .intValue ();

Try {

Socket S = New Socket (Strip, NPort);

InputStream in = s.getinputStream ();

BufferedInputStream Bisin = New BufferedInputStream (in);

While (bisin.available ()> 0) {

Byte [] b = new byte [30];

INT NLEN = Bisin.read (b);

System.out.println (New String (B, 0, NLEN);

}

}

Catch (UnknownHOSTEXCEE) {

E.PrintStackTrace ();

}

Catch (IOException E) {

E.PrintStackTrace ();

}

}

Public static void main (String [] args) {

MyClient myclient1 = new myclient (args [0], args [1]);

}

}

4. Object Serialization:

A. The so-called Object Serialization is to store the "state" of the object into a range of bit groups, and these bit groups can be used to recover objects later. Simply put, Object Serialization is allowing objects to be stored in the object. In Java, any object must be able to Serialization, you must Implements Serializable this Interface, the following is a simple program example, you can save the object to E: /POINT.SER, or return the object from E: /Point.ser.

===== Example 11 =====

Import java.io. *;

Public Class ThreeDPoint IMPLEments Serializable

{

Private Double M_DBLX, M_DBLY, M_DBLZ;

Public ThreeDpoint (double x, double y, double z)

{

m_dblx = x;

m_dbly = y;

m_dblz = z;

}

Public void Printxyz ()

{

System.out.println ("x: m_dblx);

System.out.println ("Y:" m_dbly);

System.out.println ("z:" m_dblz);

}

Public static void main (string [] args)

{

IF (Args [0]. Equalsignorecase ("W")) {

ThreedPoint threedpoint1 = new threedpoint (10, 20, 30);

Try {

FileOutputStream Fout = New FileOutputStream ("E: //point.ser");

ObjectOutputStream Oout = New ObjectOutputStream (fout);

Oout.writeObject (threedpoint1);

Oout.close ();

System.out.println ("WRITE:");

ThreeDPoint1.printxyz ();

}

Catch (Exception E) {

E.PrintStackTrace ();

}

}

ELSE IF (Args [0]. Equalsignorecase ("R")) {

Try {

FileInputStream Fin = New FileInputStream ("E: //point.ser");

ObjectInputStream Oin = New ObjectInputStream (FIN);

Object o = Oin.ReadObject ();

ThreedPoint ThreeDpoint1 = (ThreePoint) O;

Oin.close ();

System.out.println ("Read:");

ThreeDPoint1.printxyz ();

}

Catch (Exception E) {

}

}

} // end of main

}

B. In Java, a category of a particular interface, its subcategories are also considered to be in this interface due to the original injury, so many do not expire the category of the Serializable interface, in fact, SERIALIZATION.

C. Not each item in which the SERIALIZABLE interface can be used by Serialization, if this object inherits the ancestors, there is one of them can't be serialization, then this object cannot be SERIAALIZATION.

5. FORMATED I / O:

In Java's I / O, there is no so-called type, whether it is int, long, double ... Finally, it is output with String, so if you want to make numbers to be output in a specific format, you need to provide two categories java provided through Java. Text.Numberformat and Java.Text.DecimalFormat are formatted and then output.

Examples 12 brief description of how to use NumberFormat, at the beginning of the use of NumberFormat, should first obtain an entity with NumberFormat getInstance, example 12 setMaximumIntegerDigits and setMinimumFractionDigits integer and is used to set the number of decimal places, in addition to setMinimumIntegerDigits and setMaximumFractionDigits is the same function . These settings are conflicted, and Java is based on the final setting.

===== Example 12 =====

Import java.text. *;

Public class myformat {

Public myFormat () {

Numberformat nf = Numberformat.getInstance ();

Double dblnum = math.pi; system.out.println (dblnum);

Nf.setmaximumUmintegerdigits (5);

Nf.SETMINIMUMFRActionDIGITS (4);

System.out.println ("PI:" NF.Format (dblnum));

}

Public static void main (String [] args) {

MyFormat myFormat1 = new myFormat ();

}

}

Another category decimalformat is a subcategory of NumberFormat, which provides a stronger formatting function that makes our output more sampled through setting Pattern, as for the Pattern provided by Java? Detailed description in API Document ! Sample 13 only, how to use DecimalFormat.

===== Example 13 =====

Import java.text. *;

Public class mydencimalformat {

Public mydencimalformat () {

DecimalFormat DF = New DecimalFormat ("0000.000");

Double dblnum = 123.45;

System.out.println ("DBLNUM:" DBLNUM);

System.out.println ("DBLNUM:" DF.FORMAT (DBLNUM));

}

Public static void main (String [] args) {

MyDecimalformat mydencimalformat1 = new mydencimalformat ();

}

}

6. REFERENCE:

A. Java practical program design, Li Shengqi, Zhan Zhi'an, Songgang published.

B. Java I / O Technology, Elliotte Rusty Harold, Chen Jianhong, Zhang Wei, Lin Changyi, O'Reilly Published.

转载请注明原文地址:https://www.9cbs.com/read-106411.html

New Post(0)