inputstreamreader

inputstreamreader用法有哪些

小樊
90
2024-07-02 19:47:13
栏目: 编程语言

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

0
看了该问题的人还看了