以下是转大神找的原理解释:
Reader 类是 Java 的 I/O 中读字符的父类,而 InputStream 类是读字节的父类,InputStreamReader 类就是关联字节到字符的桥梁,它负责在 I/O 过程中处理读取字节到字符的转换,而具体字节到字符的解码实现它由 StreamDecoder 去实现,在 StreamDecoder 解码过程中必须由用户指定 Charset 编码格式。值得注意的是如果你没有指定 Charset,将使用本地环境中的默认字符集,例如在中文环境中将使用 GBK 编码。
所以读取数据流的时候一定要制定编码格式。
/**
* 读取文件中的内容
* @param file
* @return
*/
public static String getFileContent( File file )
{
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
reader = new BufferedReader( new InputStreamReader( new FileInputStream( file ), "UTF-8" ) );
String tmp = null;
while( ( tmp = reader.readLine() ) != null ){
sb.append( tmp );
sb.append( "\n" );
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if ( reader != null ){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* 将文本写入到文件中
* @param file
* @param content
*/
public static void writeContentToFile( File file, String content ){
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file ), "UTF-8" ) );
writer.write( content );
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if ( writer != null ){
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文详细介绍了Java中使用Reader类和InputStreamReader类进行文件读取时如何指定编码方式,确保正确处理不同字符集的文件。同时,还提供了一个实例代码来说明如何将文本内容写入文件并指定编码。

1355

被折叠的 条评论
为什么被折叠?



