inputstreamreader用法有哪些

avatar
作者
筋斗云
阅读量:0

InputStreamReader是Java中用于从InputStream读取数据的类,它将字节流转换为字符流。它有以下主要的用法:

  1. 从InputStream中读取数据,并将其转换为字符流:
InputStream inputStream = new FileInputStream("file.txt"); Reader reader = new InputStreamReader(inputStream); int data = reader.read(); while (data != -1) {     System.out.print((char) data);     data = reader.read(); } reader.close(); 
  1. 指定字符编码格式:
InputStream inputStream = new FileInputStream("file.txt"); Reader reader = new InputStreamReader(inputStream, "UTF-8"); 
  1. 使用BufferedReader包装InputStreamReader,以提高读取性能:
InputStream inputStream = new FileInputStream("file.txt"); Reader reader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(reader); String line = bufferedReader.readLine(); while (line != null) {     System.out.println(line);     line = bufferedReader.readLine(); } bufferedReader.close(); 
  1. 使用try-with-resources来自动关闭流:
try (InputStream inputStream = new FileInputStream("file.txt");      Reader reader = new InputStreamReader(inputStream)) {     int data = reader.read();     while (data != -1) {         System.out.print((char) data);         data = reader.read();     } } catch (IOException e) {     e.printStackTrace(); } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!