温馨提示×

java中inputstreamreader用法有哪些

小亿
104
2023-07-07 20:16:45
栏目: 编程语言

在Java中,InputStreamReader类是用于将字节流转换为字符流的。以下是一些InputStreamReader的常见用法:

  1. 从标准输入读取字符:
InputStreamReader reader = new InputStreamReader(System.in);
int character = reader.read();
System.out.println("Read character: " + (char) character);
  1. 从文件读取字符:
FileInputStream fileInputStream = new FileInputStream("file.txt");
InputStreamReader reader = new InputStreamReader(fileInputStream);
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
  1. 指定字符编码读取字符:
FileInputStream fileInputStream = new FileInputStream("file.txt");
InputStreamReader reader = new InputStreamReader(fileInputStream, "UTF-8");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
  1. 使用缓冲区读取字符:
FileInputStream fileInputStream = new FileInputStream("file.txt");
InputStreamReader reader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

这些只是InputStreamReader的一些常见用法,根据具体的需求和场景,还可以进行更多的操作和定制。

0