阅读量:0
InputStreamReader是Java中用于从InputStream读取数据的类,它将字节流转换为字符流。它有以下主要的用法:
- 从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();
- 指定字符编码格式:
InputStream inputStream = new FileInputStream("file.txt"); Reader reader = new InputStreamReader(inputStream, "UTF-8");
- 使用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();
- 使用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(); }