标准的输入输出流
package com.sq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
/**
* 其他流的使用
*
* 1.标准的输入、输出流
*
* 2.打印流
*
* 3.数据流
*
*/
public class OtherStreamTest {
/**
* 1.标准的输入、输出流
*
* 1.1
*
* System.in: 标准的输入流,默认从键盘输入
*
* System.out: 标准的输出流,默认从控制台输出
*
* 1.2
*
* System 类的 setIn(InputStream is) / setOut(PrintStream) 方式重新指定输入和输出的流。
*
* 1.3 练习: 从键盘输入字符串,要求读取到的整行字符串转换成大写输出,然后继续进行输入操作, 直至当输入"e"或者"exit"时,退出程序。
*
* 方法一:使用 Scanner 实现,调用 next()返回一个字符串
*
* 方法二:使用 System.in 实现。System.in ---> BufferedReader 的 readLine()
*
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true) {
System.out.println("请输入字符串:");
String 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();
}
}
}
}
/**
* idea 单元测试不支持从键盘输入(见 main 方法)
*
*/
@Test
public void test1() {}
}
package com.sq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 编写一个类似于 Scanner 类的类
*/
public class MyInput {
// Read a string from the keyboard
public static String readString() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Declare and initialize the string
String string = "";
// Get the string from the keyboard
try {
string = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// Return the string obtained from the keyboard
return string;
}
// Read an int value from the keyboard
public static int readInt() {
return Integer.parseInt(readString());
}
// Read a double value from the keyboard
public static double readDouble() {
return Double.parseDouble(readString());
}
// Read a byte value from the keyboard
public static double readByte() {
return Byte.parseByte(readString());
}
// Read a short value from the keyboard
public static double readShort() {
return Short.parseShort(readString());
}
// Read a long value from the keyboard
public static double readLong() {
return Long.parseLong(readString());
}
// Read a float value from the keyboard
public static double readFloat() {
return Float.parseFloat(readString());
}
}