An in-depth analysis of some applications of _java in Java programming

Source: Internet
Author: User

File input and output stream

file input and output streams FileInputStream and FileOutputStream are responsible for completing sequential input and output operations on local disk files.

"Example" creates a file by program, enters characters from the keyboard, ends when the character "#" is encountered, and displays all the contents of the file on the screen

Import java.io.*;
Class ep10_5{public
  static void Main (String args[]) {
    char ch;
    int data;
    try{
      fileinputstream a=new fileinputstream (filedescriptor.in);//create file input stream object
      FileOutputStream b=new FileOutputStream ("Ep10_5"); Create a file output stream object
      System.out.println ("Please enter a character, end with #:");
      while ((Ch= (char) a.read ())!= ' # ') {
        b.write (ch);
      }
      A.close ();
      B.close ();
      System.out.println ();
      FileInputStream c=new FileInputStream ("Ep10_5");
      FileOutputStream d=new FileOutputStream (filedescriptor.out);
      while (C.available () >0) {
        data=c.read ();
        D.write (data);
      }
      C.close ();d. Close ();
    catch (FileNotFoundException e) {
     System.out.println ("The file cannot be found!) ");
    }
    catch (IOException e) {}
  }
}


FileDescriptor is a class in java.io that cannot be instantiated with three static members: in, out, and err, respectively, for standard input streams, standard output streams, and standard error streams, which enable them to create file input and output streams on standard input-output streams. Implement keyboard input or screen output operation.

"Example" to implement a backup of a binary graphics file (. gif)

Import java.io.*;
Class ep10_6{public
  static void Main (String args[]) throws ioexception{
    FileInputStream a=new FileInputStream ( "Ep10_6.gif");
    FileOutputStream b=new FileOutputStream ("Ep10_6_a.gif");
    SYSTEM.OUT.PRINTLN ("File size is:" +a.available ());
    byte c[]=new byte[a.available ()];
    A.read (c); Reads the graphics file into the array
    b.write (c);//writes the data in the array to the new file
    System.out.println ("The file has been renamed and copied!") ");
    A.close ();
    B.close ();
  }

Filter Flow

FilterInputStream and FileOutputStream are direct subclasses of InputStream and OutputStream, respectively, to realize the conversion of data in a specified type or format at the same time as they are read and written. Can realize the binary byte data understanding and the coding conversion.

The two commonly used filter streams are data input stream datainputstream and data output stream dataoutputstream. The method is constructed by:

  DataInputStream (InputStream in); Creates a new input stream from the specified input stream in read data
  DataOutputStream (OutputStream out);//Create a new output stream, write data to the specified output stream

Since the DataInputStream and DataOutputStream implemented the Datainput and DataOutput two interfaces (which specify the input and output methods of the basic type data), the formatted read-write operation is independent of the specific machine. Thus, the reading and writing of different types of data are realized. It can be seen from the construction method that the input-output stream is used as the construction method parameter of the data input and output stream, that is, the filter flow must be connected with the corresponding data stream.

The DataInputStream and DataOutputStream classes provide many ways to read and write to different types of data, and readers can refer to the Java Help documentation.

"Example" writes three int-type numeric 100,0,-100 to the data file Ep10_6.dat.

Import java.io.*;
Class ep10_7{public
  static void main (string args[]) {
    string filename= "Ep10_7.dat";
    int value1=100,value2=0,value3=-100;
    try{
      //outputs different types of data to DataOutputStream and FileOutputStream connections
      dataoutputstream a=new dataoutputstream (new FileOutputStream (FileName));
      A.writeint (value1);
      A.writeint (value2);
      A.writeint (VALUE3);
      A.close ();
    }
    catch (IOException i) {
      System.out.println ("Error!") +filename);}}

After running the data file in the program directory Ep10_7.dat, opened with a text editor and found the content is binary:
All of the FF FF FF 9C.

"Example" reads three int numbers in the data file Ep10_6.dat, sums and displays.

Import java.io.*;
Class ep10_8{public
  static void main (string args[]) {
    string filename= "D:\\myjava/ep10_7.dat";
    int sum=0;
    try{
      datainputstream a=new datainputstream (New Bufferedinputstream (FileName));
      Sum+=a.readint ();
      Sum+=a.readint ();
      Sum+=a.readint ();
      System.out.println ("Three number of the and for:" +sum);
      A.close ();
    }
    catch (IOException e) {
      System.out.println ("An error occurred!) "+filename);}}}

Run Result:

Three-digit and for: 0

The ReadInt method can read 4 bytes from the input-output stream and participate directly in the operation as int data. Because you already know that there are 3 data in the file, you can use 3 read statements, but what if you only know that the data in the file is int without knowing the number of the data? Because the DataInputStream read operation throws a eofexception exception if it encounters the end of the file, the read operation can be placed in a try.

try{while
  (true)
  sum+=a.readint ();
}
catch (Eofexception e) {
  System.out.pritnln ("Three number of and for:" +sum);
  A.close ();
}

Eofexception is a subclass of IOException that is caught only when the file ends an exception, but if the end of the file is not read, the exception in the read process is IOException.

"Example" Enter an integer from the keyboard, and ask the sum of the numbers for that number.

Import java.io.*;
Class ep10_9{public
  static void Main (String args[]) throws ioexception{
    DataInputStream a=new datainputstream ( system.in);
    System.out.print ("Please enter an integer:");
    int B=a.readint ();
    int sum=0;
    int c=b;
    while (c>0) {
      int d=c%10;//Take the lowest bit
      C=C/10;//Remove the lowest bit
      sum=sum+d;//Add up everyone's and
    }
    System.out.println (b + "number of the sum =" +sum);
  }

Run Result:

Please enter an integer:
842403082 of the figures and =31

It is to be noted that the data entered is 26 to 842403082 because the input data does not conform to the format of the base type data, and the data provided from the keyboard is the byte-code representation of the character, and if you enter 26, it represents only 2 and 62 characters of byte data, not the byte code representing the integer 26.

To get an integer from the keyboard, you need to read the string first, and then use other methods to convert the string to an integer.
standard input and output

System.in, System.out, system.err these 3 standard input stream objects are defined in the Java.lang.System package, which is automatically loaded when the Java source program compiles.
Standard input: Standard input system.in is the object of the Bufferedinputstream class, when the program needs to read the data from the keyboard, only need to call the System.in read () method, which reads a byte binary data from the keyboard buffer, Returns an integer data with this byte as a low byte and a high byte of 0.
Standard output: The standard output System.out is the object of the PrintStream class of the printout stream. The PrintStream class is a subclass of the filter output stream class Filteroutputstream, which defines the method print () and println () for outputting different types of data to the screen.
Standard error Output: System.err is used to display an error message to the user and is also an error stream derived from the PrintStream class. The purpose of the ERR stream is to enable print () and println () to output information to the Err stream and display it on the screen to make it easier for the user to use and debug the program.

"Example" enters a string of characters to display and shows the class to which system.in and System.out belong.

 import java.io.*; class ep10_10{public static void Main (String args[]) {try{ byte a[]=new byte[128];
      Sets the input buffer System.out.print ("Please enter a string:"); int Count =system.in.read (a);
      Read the standard input/output stream System.out.println ("input is:"); for (int i=0;i<count;i++) System.out.print (a[i]+ "");
      The ASCII value of the output array element System.out.println (); for (int i=0;i<count-2;i++)//does not show carriage return and line feed System.out.print ((char) a[i]+ "");
      Output element System.out.println () by character mode;
      System.out.println ("The number of characters entered is:" +count);
      Class Inclass=system.in.getclass ();
      Class Outclass=system.out.getclass ();
      System.out.println ("in which class is:" +inclass.tostring ());
    System.out.println ("Out of the class is:" +outclass.tostring ()); The catch (IOException e) {}}} 

The

Run results are as follows:

Note that when you enter 3 characters, the output is displayed as 5 characters when you press ENTER. This is because a carriage return in Java is treated as two characters, one is a carriage return Ascⅱ 13, and one is a newline character with a value of 10. The GetClass () and ToString () in the program are methods of the object class, respectively, to return the corresponding class of the current object and the string representation of the current object.

Related Article

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.