InputStreamReader是Java中用于從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");
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 (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();
}