Print streams - data can be written to the file / output direction may be changed

Print streams


  • java.lang.Object
    successor java.io.OutputStream
    successor java.io.FilterOutputStream
    successor java.io.PrintStream

  • Unlike other output streams, PrintStream never throws IOException; all the characters are printed using the default character encoding platform is converted to bytes. There are many members of the method of OutputStream

  • Construction method:

    1. PrintStream (File file)
      output destination is a file;
    2. PrintStream (File file, String csn)
      newly created with the specified file name and the character set, without automatic line flushing,
    3. PrintStream (OutputStream out)
      the output destination is an output stream of bytes;
    4. PrintStream (OutputStream out, boolean autoFlush)
      Creates a new print stream.
    5. PrintStream (OutputStream out, boolean autoFlush, 1. String encoding)
      to create a new print stream.
    6. PrintStream (String fileName)
      the output destination is a file path;
    7. PrintStream (String fileName, String csn)
      Creates a specified file name and the character set, without automatic line new print stream, refreshed.
  • NOTE: If the write data, the code table queries reviewing the data, such as writing 97, a view of a method using Writer; if the write data using the print method, as will be output.

package objectStream;

import java.io.FileNotFoundException;
import java.io.PrintStream;

public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        //1.创建打印流对象,绑定输出文件路径,实际调用FileOutputStream
        PrintStream printStream = new PrintStream("b.txt");
        //2.使用writer方法测试,文件写入的是a,缺陷只能写入整数,但可以用print
        printStream.write(97);  //a
        //3.文件写入的是97
        printStream.print(97);  //a97
        //写入后换行
        printStream.println("你好呀");  //a97你好呀

        //释放资源
        printStream.close();


    }
}

Feature


  • Features: System.setOut methods may be used to change the destination (the direction of printing flow) output statement

  • static void setOut (PrintStream out) - reassigning of the standard output stream

package objectStream;

import java.io.FileNotFoundException;
import java.io.PrintStream;

public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("控制台输出");
        //创建打印流对象,绑定要输出的文件路径
        PrintStream printStream = new PrintStream("b.txt");
        //改变打印流输出方向,写入的是文件
        System.setOut(printStream);
        System.out.println("目的地改变,放入b.txt文件中");
        //释放资源
        printStream.close();


    }
}

Guess you like

Origin www.cnblogs.com/huxiaobai/p/11609368.html