JavaIO流学习总结-PrintStream基本操作练习

package io;
import java.io.PrintStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 修改日期:2020/03/31
 * 修改人:牟松
 * PrintStream基本操作练习
 * 参考链接:https://www.cnblogs.com/skywang12345/p/io_16.html
**/
public class PrintStreamTest {
 
    public static void main(String[] args) {
        //测试将字母"abcde"写入到文件"file.txt"中。
        testPrintStreamConstrutor1() ;
        //测试write(), print(), println(), printf()等接口。
        testPrintStreamAPIS() ;
    }
 
    /**
     * PrintStream(OutputStream out) 的测试函数
     * 函数的作用,就是将字母“abcde”写入到文件“file.txt”中
    **/
    private static void testPrintStreamConstrutor1() {
        //0x61对应ASCII码的字母'a',0x62对应ASCII码的字母'b'
        final byte[] arr={0x61, 0x62, 0x63, 0x64, 0x65 };
        try {
            //创建文件"file.txt"的File对象
            File file = new File("file.txt");
            //创建文件对应FileOutputStream
            PrintStream out = new PrintStream(new FileOutputStream(file));
            //将"字节数组arr"全部写入到输出流中
            out.write(arr);
            //关闭输出流
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 测试write(), print(), println(), printf()等接口。
     */
    private static void testPrintStreamAPIS() {
        try {
            // 创建文件对应FileOutputStream
            PrintStream out = new PrintStream("other.txt");
            // 将字符串“hello PrintStream”+回车符,写入到输出流中
            out.println("hello PrintStream");
            // 将0x41写入到输出流中
            // 0x41对应ASCII码的字母'A',也就是写入字符'A'
            out.write(0x41);
            //通过字节方式写到输出流中
            out.write("测试文本".getBytes());
            //通过字节方式写到输出流中,从字节流的0下标开始,写入6个字节
            out.write("测试文本".getBytes(),0,6); 
            // 将字符串"65"写入到输出流中。
            out.print(0x41);
            // 将字符'B'追加到输出流中
            out.append('B');
            // 将"CDE is 5" + 回车  写入到输出流中
            String str = "CDE";
            int num = 5;
            out.printf("%s is %d\n", str, num);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/musong1998/p/12608024.html