关于java文件流读写中文字符方法
关于向文件中写中文
向文件中写入字符比较容易,无论是字节流、字符流还有随机读写流都可以很轻松的向文件中写入中文。
对于字节流和随机读写流都可以将字符串转为字节数组写入,对于字符流则可以直接写入字符串。
字节流
FileOutputStream out=new FileOutputStream(f);
Scanner reader=new Scanner(System.in);
String s;
s=reader.nextLine();//允许有空格,回车结束
// s=reader.next();//不允许有空格
byte[] c=s.getBytes();
out.write(c);
out.write((int)'\r');
out.write((int)'\n');
字符流
FileWriter out=new FileWriter(f);
Scanner reader=new Scanner(System.in);
String s;
s=reader.nextLine();//允许有空格,回车结束
// s=reader.next();//不允许有空格
out.write(s);//直接写入字符串
out.write((int)'\r');
out.write((int)'\n');
随机读写流
*使用write(String.getBytes()), 能够正常写入
*使用writeBytes(String), writeChars(String), writeUTF(String)均产生乱码。(原因:java运行时实际上存在两种不同字符编码方式会使格式不一,nativecode编码和unicode编码)
RandomAccessFile raf= new RandomAccessFile(f, "rw");
Scanner reader=new Scanner(System.in);
String s;
s=reader.nextLine();//允许有空格,回车结束
// s=reader.next();//不允许有空格
raf.write(s.getBytes());
关于向文件中读中文问题
对于字节流,可以先把它以字节读出,再转为string类输出
FileInputStream in = new FileInputStream(f);
byte[] a=new byte[10];
in.read(a);
System.out.print(new String(a));
对于字符流可以直接读入char数组或者根据返回值强制转换为中文字符
FileReader in=new FileReader(f);
char b[]=new char[100];
in.read(b);
System.out.print(b);
FileReader in=new FileReader(f);
int a;
while((a=in.read())!=-1)
{
System.out.print((char)a);
}
对于随机读写流,可以使用readLine函数读入一行再转为中文字符串输出,或用像字节流那样用getByte()函数,再将其new String()
*使用readChar(), readUTF()均产生乱码
RandomAccessFile raf2 = new RandomAccessFile(f, "rw");
String s1,s2;
s1=raf2.readLine();
s2=new String(s1.getBytes("iso-8859-1"));//将中文字符串解析为字符数组
System.out.println(s2);