Home>

File input and output streams

File input and output streams fileinputstream and fileoutputstream are responsible for performing sequential input and output operations on local disk files.

[Example] Create a file through the program,Enter characters from the keyboard,End when the character "#" is encountered, displaying 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 a file input stream object
      fileoutputstream b=new fileoutputstream ("ep10_5");//Create a file output stream object
      system.out.println ("Please enter characters,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,This class cannot be instantiated,It contains three static members:in, out, and err, which correspond to the standard input stream, standard output stream, and standard error stream,Use them to build file input and output streams on standard input and output streams,Implement keyboard input or screen output operations.

[Example] Backup of binary graphic files (.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 ("The file size is:" + a.available ());
    byte c []=new byte [a.available ()];
    a.read (c);//Read graphics file into array
    b.write (c);//Write the data in the array to a new file
    system.out.println ("The file has been renamed and copied!");
    a.close ();
    b.close ();
  }
}

Filter stream

filterinputstream and fileoutputstream are direct subclasses of inputstream and outputstream,It can realize the specified type or format conversion of the transmitted data while reading and writing data.Can realize the understanding and encoding conversion of binary byte data.

The two commonly used filtering streams are the data input stream datainputstream and the data output stream dataoutputstream. Its construction method is:

 datainputstream (inputstream in);//Create a new input stream,Read data from the specified input stream in
  dataoutputstream (outputstream out);//Create a new output stream,Write data to the specified output stream out

Because datainputstream and dataoutputstream respectively implement the datainput and dataoutput interfaces (these two interfaces specify the input and output methods for basic types of data), the format-specific read and write operations are independent ofThus, reading and writing of different types of data is realized.Can be seen from the construction method,The input and output streams are used as the method parameters of the data input and output streams.That is, as a filtered stream, it must be connected to the corresponding data stream.

The datainputstream and dataoutputstream classes provide many read and write methods for different types of data.For details, please refer to java's help documentation.

[Example] Write three int numbers 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 {
      //Connect dataoutputstream and fileoutputstream to output different types of data
      dataoutputstream a=new dataoutputstream (new fileoutputstream (filename));
      a.writeint (value1);
      a.writeint (value2);
      a.writeint (value3);
      a.close ();
    }
    catch (ioexception i) {
      system.out.println ("An error occurred!" + filename);
    }
  }
}

After running, the data file ep10_7.dat is generated in the program directory. After opening it with a text editor, the content is binary:

00 00 00 64 00 00 00 00 ff ff ff 9c.

[Example] Read three int numbers in the data file ep10_6.dat, sum them up and display them.

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 (new fileinputstream (filename)));
      sum +=a.readint ();
      sum +=a.readint ();
      sum +=a.readint ();
      system.out.println ("The sum of the three numbers is:" + sum);
      a.close ();
    }
    catch (ioexception e) {
      system.out.println ("An error occurred!" + filename);
    }
  }
}

operation result:

The sum of three numbers is:0

The readint method can read 4 bytes from the input and output stream and directly participate in the operation as int data.Since you already know that there are 3 data in the file, you can use 3 read statements,But what if you only know the int data in the file and not the number of data?Because the read operation of datainputstream will throw eofexception if it encounters the end of the file, you can put the read operation in try.

try {
  while (true)
  sum +=a.readint ();
}
catch (eofexception e) {
  system.out.pritnln ("The sum of the three numbers is:" + sum);
  a.close ();
}

eofexception is a subclass of ioexception and will only be caught when the end-of-file exception occurs.But if you do n’t read the end of the file,An exception during reading is an ioexception.

[Example] Enter an integer from the keyboard,Find the sum of the digits of the 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;//accumulate the sum of everyone
    }
    system.out.println (b + "Sum of the numbers of all bits =" + sum);
  }
}

operation result:

Please enter an integer:26
Sum of numbers of 842403082=31

have to be aware of is,The input data 26 is 842403082 because the input data does not conform to the format of the basic type of data.The data provided from the keyboard is a bytecode representation of the characters,If you enter 26, it only represents byte data of 2 and 6 characters.Instead of the bytecode representing the integer 26.

To get an integer from the keyboard you need to read the string first,Use other methods to convert strings to integers.

Standard input and output

The three standard input stream objects, system.in, system.out, and system.err, are defined in the java.lang.system package. These three objects are automatically loaded when the java source program is compiled.

Standard input:The standard input system.in is an object of the bufferedinputstream class,When the program needs to read data from the keyboard,Just call the read () method of system.in,This method reads a byte of binary data from the keyboard buffer.Returns this byte as the low-order byte,Integer data whose high byte is 0.

Standard output:The standard output system.out is an object of the printstream class printstream.The printstream class is a subclass of the filteroutputstream class,It defines the methods print () and println () that output different types of data to the screen.

Standard error output:system.err is used to display error messages to users,It is also an error stream derived from the printstream class.The role of the err stream is to cause print () and println () to output information to the err stream and display it on the screen.To facilitate the user to use and debug the program.

[Example] Enter a string of characters to display,And show the classes that system.in and system.out belong to.

import java.io. *;
class ep10_10 {
  public static void main (string args []) {
    try {
      byte a []=new byte [128];//Set the input buffer
      system.out.print ("Please enter a string:");
      int count=system.in.read (a);//Read standard input and output streams
      system.out.println ("The input is:");
      for (int i=0;i<count;i ++)
        system.out.print (a [i] + "");//Ascii value of the output array elements
      system.out.println ();
      for (int i=0;i<count-2;i ++) //Do not display carriage returns and line feeds
        system.out.print ((char) a [i] + "");//Output elements as characters
      system.out.println ();
      system.out.println ("The number of characters entered is:" + count);
      class inclass=system.in.getclass ();
      class outclass=system.out.getclass ();
      system.out.println ("in belongs to the class:" + inclass.tostring ());
      system.out.println ("out belongs to the class:" + outclass.tostring ());
    }
    catch (ioexception e) {}
  }
}

The results are shown below:

have to be aware of is,After entering 3 characters and pressing enter,The output is displayed as 5 characters. This is because carriage returns are treated as two characters in java.One is a carriage return with ascII of 13,One is a newline with a value of 10.Getclass () and tostring () are methods of the object class in the program.The effect is to return the class corresponding to the current object and the string representation of the current object.

  • Previous Summary of Winform's method for obtaining file path in C #
  • Next Parsing text boxes and text areas in Java graphical programming