Getting Started in Java Language - The input and output operation of Chapter 9 Java

zhaozj2021-02-17  57

Chapter 9 Java Input Output

9.1 Java input and output flow

The program language is mentioned; Copy; the way of interacting with the file system; Java is an example. We will see how Java is in charge of the standard file (including stdin, st, stderr). When you open a small program on the network, you must pay attention to the direct file input and output is the key to the incomplete factor. Most of the number of users set their browses to let you visit their file system, but is it? Copy; Do not let you visit. Of course, if you drive your internal application, you also need to access the document directly.

The standard input into the output of Unix users, or otherwise, the user (such as DOS), which is based on the command line system, knows the meaning of the markup input. The standard input file is a keyboard, and the standard output file is your terminal screen. The standard error errors also points to the screen. If there is a need, it can point to another document and the normal output division.

The system-wide Java passes the functionality of the interview with the standard input. The three files mentioned above are in this systemic class: stdin system.in is implemented in an instance of the InputStream class, you can use read () and skip (long n) two members. Read () Let you read a byte from the input, Skip (long n) lets you skip N bytes in the input.

STOUT System.out is made for PrintStream to realize stdout, you can use print () and println () two members. These two functions support Java's any-based type as a parameter.

STDERR System.err STDERR with Stdout. Like System.out, you can visit the PrintStream membership function.

9.2 Moderator input Example

There is an example in this, the function is like a CAT or TYPE in UNIX:

Import java.io. * class mycat {public void main (string args []) throws oException {Int b; int count = 0; while ((b = system.in.read ())! = -1) {count ; System.out.print ((char) b);} system.out.println (); // blank line system.err.println ("counted" count "Total Bytes.");}}

9.3 Putong input and output class

In addition to the basic keyboard input and screen output, we need to enter the output of the file. We will learn to learn a few categories: l FileInputStream L DataInputStream L FileOutputStream L DataOutputStream

As a reference, and then lists a copy; class-specific applications:?? L PipedInputStream l BufferedInputStream l PushBackInputStream l StreamTokenizer l PipedOutputStream l BufferedOutputStream l RandomAccessFile we are not here to discuss this copy; class, but you can JAVA_HOME / src / java / io View the member function definition of each class in the directory.

9.4 file

When we pay the documentation, you need to know the road? Copy; related to file? Information. File class? Copy; one? Copy; member function to operate the document and get a copy; information about the document.

9.4.1 Creating a new file object

You can create a new document pair with three justctions:

File myfile; myfile = new file ("etc / motd");

or

Myfile = new file ("/ etc", "motd"); // More useful if The Directory or FileName Are Variables

or

File mydir = new file ("/ etc"); myfile = new file (MyDir, "MOTD");

These three methods will depend on the way you visit the documents. For example, if you use only one file in the application, the structure of the first creation of documents is the most easy. But if you open a number of files in the same directory, the second or third types of structures are better? Copy ;.

9.4.2 Document Test and Use

One? Copy; You create a file object, you can use the following member functions to get the meticulum correlation information:

Document name L string getname () L string getpath () l string getabslutepath () l string getparent () l Boolean Renameto (File NewName)

Document Test l Boolean EXISTS () L Boolean Canread () l Boolean IsFile () L Boolean Isdirectory () l Boolean Isabsolute ()

General Will Information L Long LastModified () L Long length ()

Directory L Boolean Mkdir () L String [] list ()

9.4.3 Delivery information acquired

This is an independent version of the basic information of the document, and the document is passed through the command line.

Import java.io. *; class fileinfo {file filetocheck; public static void main (string args []) throws oException {if (args.length> 0) {for (int i = 0; i

InputStream SequenceInputStream FileInputStream PipedinputStream ByterrayinputStream FileterInputStream StringBufferInputStream

DataInputStream LinenumberInputStream PushbackInputStream BufferedInputStream has several classes to be used to handle file input. The lower surface is the layers of the file input class:

9.5.1 FileInputStream object

FileInputStream typically represents a text file for sequential access. By using FileInputStream you can access one by section of the file, several bytes or whole files.

9.5.2 Open FileInputStream

Open the stream fileInputStream for a file, you must transfer the document name or document to the structure:

FileInput Stream MyFileStream; MyFileStream = New FileInputStream ("/ etc / motd");

You can also read document information from FileInputStream from the next side:

File Myfile; fileinputsteam myfilestream; myfile = new file ("/ etc / motd"); myfilestream = new fileInputstream (myfile);

One? Copy; FileInputStream Enter the stream to open, you can read the information from the inside. The read () member function has the following options: l int tent () // reads one byte // return -1 at endte // RETURN-1 At End of Stream L int in (byte b []) // Fills entire array, if Possible // Returns Number of Bytes Read // Returns -1 if End of Stream Is Reached

L int tent (Byte B [], int offset, int LEN) // reads len bytes INTO B Starting at b [Offset] // rturns number of bytes read, // or -1 if End of Stream is Reached.

9.5.3 Close FileInputStream

When you finish a document, you can choose two ways to turn off: explicitly closed and implicit closed, implicit shutdown is the function of automatic garbage.

Explicit closure is as follows: myfilestream.close ();

9.6: Display a file

If the access rights of the feature are enough, you can display the contents of the document in the TextArea object.

The lower side is the program block of display files:

FileInputStream Fis; PUBLIC VOD INIT () {byte B [] = New Byte [1024]; INT I; // Make It Big Enough or Wait Until You // KNOW The size of the file string s; try {FIS = New fileInputStream ("/ etc / motd");} catch (filenotfoundexception e) {/ * do something appropriate * /} try {i = fis.read (b);} catch (ooException e) {/ * do something appropriate * /} s = new string (b, 0); ta = new textarea (s, 5,40); add (ta);}

9.7 DataInputStreams

DataInputStreams is not much different from FileInputStreams. The DATA stream can be directly read to any variable type, such as floating point, integer, and characters. In general, the DataInputStream stream is used for binary files.

9.7.1 Opening and closing DataInputStreams

When you open and turn off the DataInputStreams object, its method is the same as FileInputStreams:

DataInputStreams MyDataStream; FileInputStreams MyFileStream;

// Get a file handle myfilestream = new fileinputstream ("/ usr / db / stock.dbf"); // open, or "chain" a data input file mydatastream = new DataOutputStream (MyFileStream);

// NOW We can use Both INPUT streams to access ou file // j (if we want to ...) MyFileStream.read (b); i = mydatastrea.readint (); // Close the data friel explicity or // always Close the "Topmost" File Stream mydatastream.close (); myfilestream.close ();

9.7.2 Read DataInputStreams

When you visit files from the DataInputStreams stream, you can use the membership function read () with the FileInputStream stream. But you can also read the different types of data using other ways to visit the method:

l byte readByte () l int readUnsignedByte () l short readShort () l int readUnsighedShort () l char readChar () l int readInt l long readLong () l float readFloat () l double readDouble () l String readLine ()

Read the corresponding data objects in each of the members. As a string readline () member function, you can use / n, / r, / r / n, or EOF as a character? REG; end.

Read a long integer, such as:

Long serialno; ... serialno = mydatathastream.readlong ();

9.8 URL input flow

In addition to the basic documentation, Java also mentioned. Copy; the function of accessing the object with the URL of the network. In this example, we use the getDocumentbase () member function and explicitly specify the URL object to visit the sound and image.

String imagefile = new string ("images / duke / t1.gif"); images [0] = getImage (GetDocumentBase (), ImageFile ();

If we are willing, you can use the URL: URL ImageSource; ImageSource = New URL ("http://555-1212.com/~info"); Images [0] = GetImage (ImageSource, "Duke / T1.gif") ;

We can open an input stream for the corresponding URL. For example, the next program includes an data file: inputStream is; byte buffer [] = new byte [24]; is = new url () .openStream () .openStream ();

Now we can use IS, just like the use of FileInputStream pairs: Is.Read (buffer.0, buffer.length);

Note: Is there? Copy; User sets his navigation security property, you can't let your program visit their documents.

9.9 OutputStreams

We talked about reading data, what is it now written? As in the input stream, there is a similar level structure of the output stream: OutputStream

FileOutputStream PiredOutputstream ByteArrayoutputStream Filteroutputstream

DataOutputStream PrintStream Bufferedoutputstream

We will analyze the FileOutputStream and DataOutputStream class to finish the outlining issues I have encountered. Its output package contains more information and member functions. The source file like the stream is lost, this? Copy; files in $ java_home / src / java / IO directory.

9.9.1 FileOutputStream Class

FileOutputStream pairs are used to write data to a text file. When you enter the message, you have to open this file first before you can write this document.

9.9.2 Open a FileOutputStream object

To open a FileOutputStream object, like to open a input stream, you can make characters? Reg; or file pair as parameters: fileoutputstream myfilestream; myfilestream = new fileoutputstream ("/ etc / motd");

I can use it in the stream, you can use: file myfile; fileoutputstream myfilestream; myfile = new file ("/ etc / motd"); myfilestream = new fileoutputstream (MyFile);

9.9.3 Write a stream

One? Copy; the document is opened, you can write one of the written () function to the document; data. Like the READ () function of the input stream, you can have three ways: l void write (int b); // Writes out one byte l void write (byte b []); // Writes Out Entire Array L Void Write (Byte B [], int loongth); // Write out length BYTES OF B [], Starting At B [Offset]

9.9.4 Close a FileOutputStream object

Turn off the output and shutdown input flow method, you can use the Optical Method: myfilestream.close (); you can also turn the system to close it.

9.10 cases: storage information

There is a program below, allowing the user to enter a copy; a name and a call number. Every last name and number will be added in the document. Use the household "DONE" button to tell the complaint system full list has been completed.

One? Copy; User Enterprise Inframe, the program will create an output file and display it or print. E.g:

555-1212, TOM 123-456-7890, PEGGY L. 234-5678, Marc 234-5678, Ron 876-4321, Beth & Brian 33.1.42.45.70, Jean-Marc Below is the source code of the program: Import Java.IO. *;

//Phones.java // A Simple Database Creation Program

class Phones {static FileOutputStream fos; public static final int lineLength = 81; public static void main (String args []) throws IOExciption {byte [] phone = new byte [lineLength]; byte [] name = new byte [lineLenght]; INT i; fos = new fileoutputstream ("Phone.NumBers"); while (true) {system.err.println ("Enter a name"); Readline (Name); if ("DONE) ".equalsignorecase (New String (Name, 0, 0, 4)))) {Break;} System.err.Println (" Enter the Phone Number "); Readline (Phone); for (i = 0; Phone [i] ! = 0; i ) {fos.write (phone [i]);} fos.write (','); for (i = 0; Name [i]! = 0; i ) {fos.write (Name [ I]);} fos.write ('/ n');} fos.close ();}

Private static void ready (byte line []) throws = 0, b = 0;

WHILE ((i

9.11 BUFFEREDOUTPUT stream

If you have a lot of data you are handling, or write a lot of small data to files, you can use a bufferedoutput stream. BUFFEREDOUTPUT streaming Copy; and the FileOutputStream class write operation method, but all outputs are stored in a buffer area. When you fill in the buffer, it will write a magnetic disk once. Or you are active to write the buffer zone into the magnetic disk.

9.11.1 Creating a bufferedoutput stream

If you want to create a bufferedoutput, you need a FileoutPut stream first. The buffer is then linked to FileOutput stream: FileOutputStream myFileStream; BufferedOutputStream myBufferStream; // get a file handle myFileStream = new FileOutputStream ( "/ usr / db / stock.dbf"); // chain a buffered output stream myBufferSSstream = new BufferedOutputStream ( MyFileStream); 9.11.2 Update and close Bufferedoutput

And the Putong FileOutput stream, the write-to-write disk operation in the BufferedOutput stream is not a check. Want to write the data in the buffer to disk before the program ends? // close the data file explicitly // always close the "Topmost" File Stream MyBufferstream.close (); myfilestream.close ();

9.12 DataOutput stream

And DataInputStream: Java also mentioned Copy; DataOutput stream. Use the DataOutput stream, we can write binary data to files.

9.12.1 Opening and closing the Dataoutput stream object

Open and turn off the DataOutput stream pair and open, turn off FileOutput stream to the icon: DataOutputStream MyDataStream; bufferedstream myfilestream; bufferedoutputstream myBufferstream;

// get a file handle mhyFileStream = new FileOutputStream ( "/ usr / db / stock.dbf"); // chain a buffered output stream (for efficiency); myBufferStream = new BufferedOutputStream (myFileStream); // chain a data output file MyDataStream = New DataOutputStream (MyBufferstream);

// Now We can use Both Input Streams to Access Our File // (IIIF WA Want To ...) MyBufferstream.write (b); MyDataStream.writeInt (i);

// close the data file explicitly // always colse the "topmost" file stream mydatastream.close (); mybuffersstream.close (); MyFileStream.close ();

9.12.2 Writing data to DataOutput

The Write () function in the FileOutput stream is suitable for DataOutput streams. You can also see the similar function method of the DataInput stream: l Void WriteBoolean (Boolean V) l void WritebyTe (int V) l void Writecher (int V) l void WriteInt (int V) l void writefloat (Float V) l Void WriteBLE (String S) L Void WriteChars (String S) There are two options: Byte and Char. Remember byte is 8 digits and char is 16 digits. If you want to use the advantages of Unicode characters, you should use the WriteChars () function.

9.12.3 Output

Another one of the other functions commonly used when using binary data is output is Size (). This function returns to the total number of bytes of writing documents. You can also use the size () function to divide the data file into four blocks, for example: ... int Bytesleft = mydatastream.size ()% 4; for (INT i = 0; i

9.13 random access documents

We read files often not read from head to tail. You also like to make a textbook as a data library, after reading a record, jump to another record, and they are in the same place in the document. Java mentioned; the RandomaccessFile class allows you to operate this type of input.

9.13.1 Creating a random access document

Open the random access document: L Use the document name myrafile = new randomaccessfile (String name, string mode); l Use the document object MyRafile = new randomaccessfile (File File, String Mode);

The MODE parameter determines the right to access the file, such as read reading 'R' or reads writing 'WR', etc.

For example, we open a database update data: randomaccessfile myrafile; myRafile = new randomaccessfile ("/ usr / db / stock.dbf", "rw");

9.13.2 Access Information

The RandomaccessFile object reads and write operations and DataInput / DataOutput objects are operative. You can use all READ () and Write () functions that are now in DataInputStream and DataOutputStream.

There are also several functions to help you move the pointer in the file: l Long getfilepointer (); return to the front pointer L Void Seek (long POS); place the file normally to an abscribe. The address is the deviation of the part of the file header. Address 0 indicates the opening of the file. l long length (); return to the length of the file. Address "Length ()" represents the end of the file. 9.13.3 Adding information

You can use a random access file to add information mode: myRafile = new randomaccessfile ("/ tmp / java.log", "rw"); myrafile.seek ()); // any subsequent Write () S Will Be Appended to the File

9.13.4 Characterization The following is an example of chasing characters after the file has been stored in the document: Import java.ioeException; import java.io.randomaccessFile;

class raTest {public static void main (String args []) throws IOException {RandomAccessFile myFAFile; String s = "Information to Append / nHi mom / n!"; // open our random access file myRAFile = new RandomAccessFile ( "/ tmp / Java.log "," rw "); // move to the end of the file myrafile.seek (myRafile.Length ()); // start appending! myrafile.writebytes (s);

MyRafile.close ();}}

chapter summary

1. Java passes through the system category to the functionality of the interview margin input. 2. You can create, read, and write files.

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

New Post(0)