1、 获取输入流的四种方式
1) 从文件中读
public static InputStream getInputStream() throws IOException {
InputStream inputStream = new FileInputStream("E:\\javacode\\src\\jing\\able\\Java\\IO\\输入流测试文件");
return inputStream;
}
2) 从网络上读
public static InputStream getInputStream() throws IOException {
Socket socket = new Socket("www.baidu.com",80);//域名加端口号
OutputStream os = socket.getOutputStream();
Writer writer = new OutputStreamWriter(os,"UTF-8");
PrintWriter printWriter = new PrintWriter(writer,false);
printWriter.printf("GET/HTTP/1.0\r\n\r\n");
printWriter.flush();
InputStream inputStream = socket.getInputStream();
return inputStream;
}
3) 从内存上读
public static InputStream getInputStream() throws IOException {
byte[] bytes = "我是内存上的一段空间".getBytes("UTF-8");
InputStream inputStream = new ByteArrayInputStream(bytes);
return inputStream;
}
4) 从标准输入读 (从键盘读入)
注意:需要手动输入 ctrl + D (或者ctrl + Z )才能终止键盘输入
public static InputStream getInputStream() throws IOException {
InputStream inputStream = System.in ;
return inputStream;
}
2、从字节流中最终获得字符数据的三种方式
1) 直接通过字节方式读,然后程序进行字符编码(buffer 大小<数据长度/精确控制字符都比较麻烦)
public static String resultInputStrem(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
int len = is.read(buffer);
String message = new String(buffer,0,len,"UTF-8");
return message;
}
2)把 Stream 转化为 Reader,进行字符形式直接读取
public static String resultInputStrem(InputStream is) throws IOException {
Reader reader = new InputStreamReader(is,"UTF-8");
char[] buffer = new char[1024];
int len = reader.read(buffer);
String message = new String(buffer,0,len);
return message;
}
3) 把 Stream 转化为 Reader,进行字符形式读取 BufferedReader readLine (和第二种差不多)
public static String resultInputStrem(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
Reader reader = new InputStreamReader(is,"UTF-8");
char[] buffer = new char[1024];
int len ;
while((len = reader.read(buffer))!=-1){
sb.append(buffer,0,len);
}
String message = sb.toString();
return message;
}
4) Scanner
public static String resultInputStrem(InputStream is) throws IOException {
Scanner scanner = new Scanner(is, "UTF-8");
return scanner.nextLine();
}