处理流之三:标准输入、输出流
System.in和System.out分别代表了系统标准的输入和输出设备
- 默认输入设备是:键盘,输出设备是:显示器
- System.in的类型是InputStream
- System.out的类型是PrintStream,其是OutputStream的子类 FilterOutputStream 的子类
- 重定向:通过System类的setIn,setOut方法对默认设备进行改变。
- public static void setIn(InputStream in)
- public static void setOut(PrintStream out)
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
直至当输入“e”或者“exit”时,退出程序。

处理流之四:打印流
实现将基本数据类型的数据格式转化为字符串输出
打印流:PrintStream和PrintWriter 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
PrintStream和PrintWriter的输出不会抛出IOException异常
PrintStream和PrintWriter有自动flush功能
PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。 在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
System.out返回的是PrintStream的实例


处理流之五:数据流
用于读取或写出基本数据类型的变量或字符串




1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
|
public class OtherStreamTest {
public static void main(String[] args) { BufferedReader br = null; try { InputStreamReader isr = new InputStreamReader(System.in); br = new BufferedReader(isr);
String data; while (true) { System.out.println("请输入字符串:"); data = br.readLine(); if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) { System.out.println("程序结束"); break; } String upperCase = data.toUpperCase(); System.out.println(upperCase); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
@Test public void test2() { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(new File("C:\\Data\\IDM\\Java学习\\尚硅谷Java\\test.txt")); ps = new PrintStream(fos, true); if (ps != null) { System.setOut(ps);
} for (int i = 0; i <= 255; i++) { System.out.print((char) i); if (i % 50 == 0) { System.out.println(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } }
@Test public void test3() throws IOException { DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); dos.writeUTF("刘建辰"); dos.flush(); dos.writeInt(23); dos.flush(); dos.writeBoolean(true); dos.flush(); dos.close();
}
@Test public void test4() { DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream("data.txt")); String name = dis.readUTF(); int age = dis.readInt(); boolean isMale = dis.readBoolean();
System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("isMale = " + isMale); } catch (IOException e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
|