您的位置:首页 > 编程语言 > Java开发

8.Java基础:常见IO流----->字符流中的转化流:OutputStreamWriter、InputStreamReader

2016-09-02 21:31 483 查看
1.这两个是转换流,他们的作用

1.在字节与字符之间做转换.

2.可以指定编码进行读写操作。



[b]2.InputStreamReader:字节流通向字符流的桥梁
[/b]

构造
newInputStreamReader(InputStream is);

public class InputStreamReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo</span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span>
<span style="white-space:pre">	</span>public static void main(String[] args) throws IOException {
//第一种方案
InputStream is = System.in; //获取一个从键盘读取信息的输入流
byte[] by= new byte[2];
int length = is.read(by);

System.out.println(new String(by, 0, length));

////第二种方案,手动完成
//在System.in外层包装一个流,这个流是字符流,可以直接使用字符							流,读取字符
InputStreamReader isr = new InputStreamReader(System.in);
char[] ch = new char[10];

int length = isr.read(ch); //一次读取一个字符
System.out.println(new String(ch, 0, length));
//System.out.println(String.valueOf(ch, 0, length)); //和						上句话效果一样
}
}


3.OutputStreamWriter:是字符流通向字节流的桥樑

构造

newOutputStreamWriter(OutputStream os)         

//向控制台写入一个汉字
public class BufferedReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo </span><span style="font-family: Arial, Helvetica, sans-serif;">{</span>
<span style="white-space:pre">	</span>public static void main(String[] args) throws IOException {
<span style="white-space:pre">		</span>OutputStreamWriter osw = new OutputStreamWriter(System.out);
<span style="white-space:pre">	</span>osw.write("我是一个好人");

<span style="white-space:pre">	</span>osw.flush();
<span style="white-space:pre">	</span>osw.close();
<span style="white-space:pre">	</span>}
}


4.解决编码乱码

1.原因:new InputStreamReader(InputStream is) 使用默认字符集,与系统默认编码不一样,出现乱码

解决方案:

InputStreamReader(InputStream in, String charsetName) 

创建使用指定字符集的 InputStreamReader。

public class InputStreamReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo</span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span>
//读取e盘下a.txt文件
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("e:/a.txt");
InputStreamReader isr = new InputStreamReader(fis); //使用UF-8字符集读取

//读取文件内容
while (true) {
int code = isr.read(); //一次读取一个
if (code == -1) {
break;
}
System.out.println((char)code);
}

}
}

2.使用OutputStreamWriter时,如果也有编码问题  

解决方案: new OutputStreamWriter(OutputStream os,String charsetname);

public class InputStreamWriter<span style="font-family: Arial, Helvetica, sans-serif;">Demo </span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span>
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("e:/a.txt",true);
OutputStreamWriter osw = new OutputStreamWriter(fos);

osw.write("中国");
osw.flush();
osw.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐