IO 集合中获取流的几种方式

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();

}

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值