我讀到InputStream用於基於字節的讀取,它一次讀取1個字節。 InputStreamReader用於基於字符的讀取,因此它一次讀取一個字符,因此不需要先將其轉換爲int,然後再讀取它。java中的InputStream和InputStreamReader之間的區別
這裏是使用InputStream進行讀取。
InputStream input=new FileInputStream("D:/input.txt");
int c;
while((c=input.read())!=-1)
{
System.out.print((char)c);
}
這裏使用的InputStreamReader
InputStream input=new FileInputStream("D:/input.txt");
reader=new InputStreamReader(input,"UTF-8");
int c;
while((c=reader.read())!=-1)
{
System.out.print((char)c);
}
是什麼InputStream
和InputStreamReader
區別讀書?在這兩種情況下,我必須使用int
然後閱讀它,最後如果我想打印那些數據,我必須使用「(char)c」進行轉換。
那麼使用InputStreamReader
有什麼好處呢?
不同之處在於'InputStream'本身不會處理大於127的輸入值。嘗試在測試輸入中添加一些中文字符,它們將使用'InputStream'版本打印爲兩個字節。 – markspace