JavaBase-IO流-标准输入,输出流、打印流、数据流
发布日期:2021-04-30 21:03:36 浏览次数:106 分类:精选文章

本文共 2644 字,大约阅读时间需要 8 分钟。

标准输入输出流是Java程序与外部设备进行通信的重要桥梁,理解它们的特性和使用方法对任何Java程序员都是必不可少的。

标准输入输出流

在Java环境中,System.inSystem.out分别代表标准输入和输出设备。默认情况下,输入设备是键盘,输出设备是显示器。

  • System.in的类型是InputStream,用于从键盘读取输入数据。
  • System.out的类型是PrintStream,是OutputStreamFilterOutputStream的子类,提供了便捷的数据输出功能。

通过System.setInSystem.setOut方法,可以改变默认的输入输出设备。例如:

public static void setIn(InputStream in) {}public static void setOut(PrintStream out) {}

打印流

PrintStream和PrintWriter是Java中常用的打印流,它们提供了多种数据类型的输出功能。PrintStream主要用于处理基本数据类型和字符串的输出,而PrintWriter则提供了更高级别的字符操作功能。

  • PrintStream

    • 提供print()println()方法,用于输出不同数据类型的值。
    • 打印流的输出不会抛出IOException异常。
    • 支持自动刷新功能。
  • PrintWriter

    • 同样提供多种数据类型的输出方法。
    • 提供更灵活的字符操作,如缓冲和字符串格式化。
    • 使用PrintWriter可以指定字符编码,确保在不同平台上都能正确显示字符。

需要注意的是,PrintStream使用平台默认字符编码进行转换,而在需要自定义字符编码时,应使用PrintWriter

数据流

在Java中,DataInputStreamDataOutputStream是处理基本数据类型和String数据的专用数据流。它们可以分别连接到InputStreamOutputStream子类流,以实现数据的读写。

  • DataInputStream:提供读取基本数据类型和String的方法,例如:

    boolean readBoolean();byte readByte();char readChar();float readFloat();double readDouble();short readShort();long readLong();int readInt();String readUTF();void readFully(byte[] b);
  • DataOutputStream:提供写入基本数据类型和String的方法,例如:

    void writeBoolean(boolean b);void writeByte(int v);void writeChar(int v);void writeFloat(float v);void writeDouble(double v);void writeShort(int v);void writeLong(long v);void writeInt(int v);void writeUTF(String v);

数据流的使用示例

以下是使用DataInputStreamDataOutputStream的示例代码:

@Testpublic void test3() {    DataOutputStream dos = null;    try {        dos = new DataOutputStream(new FileOutputStream("dos.txt"));        dos.writeBoolean(true);        dos.flush();        dos.writeUTF("打发斯蒂芬");        dos.flush();        dos.writeInt(1);        dos.flush();    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        if (dos != null) {            try {                dos.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}@Testpublic void test4() {    DataInputStream dis = null;    try {        dis = new DataInputStream(new FileInputStream("dos.txt"));        System.out.println(dis.readBoolean());        System.out.println(dis.readUTF());        System.out.println(dis.readInt());    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        if (dis != null) {            try {                dis.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

通过以上内容,可以看出Java中的标准输入输出流、打印流和数据流在程序设计中的重要性。掌握这些工具能够帮助开发者更方便地与外部设备进行数据交换,提升程序的功能和用户体验。

上一篇:Spring的依赖注入和Spring Bean的配置及常用属性
下一篇:【剑指offer】面试题49:丑数

发表评论

最新留言

很好
[***.229.124.182]2026年06月01日 18时34分09秒