在java中一个字符等于两个字节,操作字符有Reader和Writer


1.字符输出流
看源码:
public abstract class Writer implements Appendable,
Closeable, Flushable {
这里实现了Appendable(这个表示类容可以被追加,String 类也实现了这个)
1.向文件中写入数据
public class WriterDemo {
public static void main(String[]
args) throws Exception{
File f= new File("f:"+File.separator +"a.txt" );
Writer w= null;
w= new FileWriter(f);
String str= "hello like";
w.write(str);
w.close();
}
}
这个和OutputStream 没有什么不同,唯一的好处就是可以直接接收字符串了,不用转byte数组了
2.使用FileWriter追加内容
public class WriterDemo1
{
public static void main(String[]
args) throws Exception{
File f= new File("f:" +File.separator+"a.txt");
Writer w= new FileWriter(f,true);
String str= "\r\n----Hello world";
w.write(str);
w.close();
}
}
3.字符输入流 Reader
看源码:public abstract class Reader implements Readable,
Closeable {
public class ReaderDemo
{
public static void main(String[]
args) throws Exception{
File f= new File("f:"+File.separator +"a.txt" );
Reader r= null;
r= new FileReader(f);
char c[]=new char[1024];
int len=r.read(c);
r.close();
System. out.println(new String(c,0,len));
}
}
结果:
hello like
----Hello world
如果不知道文件的长度,也可以像字节流那样做
public class ReadDemo1
{
public static void main(String[]
args) throws Exception{
File f= new File("f:" +File.separator+"a.txt");
Reader r= new FileReader(f);
int len=0;
int temp=0;
char c[]=new char[1024];
while((temp=r.read())!=-1){
c[ len]=(char)temp;
len++;
}
r.close();
System. out.println( new String(c,0,len ));
}
}
结果:
hello like
----Hello world