Standard Input,Output Stream 标准输入输出流
- System.in 系统标准输入流
所属InputStream Scanner(System.in);
默认从键盘获取输入信息
- System.out 系统标准输出流
所属PrintStream,是OutputStream的子类,FilterOutputStream System.out.println();
默认从控制台输出信息
- static void setInt(InputStream input) static void setOut(OutputStream output) 重新指定输入和输出的流
使用Scanner实现程序
static void inputPractice(){ // 使用Scanner实现 Scanner input = new Scanner(System.in); String text = "null"; while( !(text.equals("e") || text.equals("exit")) ){ System.out.println("请输入字符串"); text = input.nextLine(); System.out.println(text.toUpperCase()); }
input.close(); }
用System.in实现
static void inputPractice() throws Exception { // 使用System.in实现 InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); while( true ){ System.out.println("请输入字符串"); String text = bufferedReader.readLine(); System.out.println(text.toUpperCase()); if ("e".equalsIgnoreCase(text) || "exit".equalsIgnoreCase(text)){ System.out.println("程序结束"); break; } } bufferedReader.close(); }
打印流
PrintStream PrintWriter
- 各种print() 和 println()重载 用于多种数据类型的输出
- PrintStream和PrintWriter 不抛异常,自带flush
- PrintStream打印所有都是以平台默认字符编码转换字节
写入字符非字节的情况使用PrintWriter
- System.out 返回的是PrintStream的实例
向指定文件输出数据
static void printStream(String srcPath) throws Exception { OutputStream outputStream = new FileOutputStream( new File(srcPath) ); PrintStream printStream = new PrintStream(outputStream,true); if ( printStream != null) System.setOut(printStream); for (int i = 0; i < 255; i++) { System.out.print((char)i + "\t"); if ((i + 1) % 10 == 0) System.out.println(); } printStream.close(); }
数据流
DataInputStream
DataOutputStream
写入数据和读取数据
static void printData() throws Exception { DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(new File("sample.txt"))); dataOutputStream.writeUTF("阿伟输了!!!"); dataOutputStream.flush(); dataOutputStream.writeInt(1001); dataOutputStream.flush(); dataOutputStream.writeBoolean(true); dataOutputStream.flush(); dataOutputStream.close(); } static void readData() throws Exception { DataInputStream dataInputStream = new DataInputStream(new FileInputStream(new File("sample.txt"))); // 读取数据顺序,要按写入顺序保持一致 String str = dataInputStream.readUTF(); int i = dataInputStream.readInt(); boolean b = dataInputStream.readBoolean(); System.out.println(str); System.out.println(i); System.out.println(b); dataInputStream.close(); }