2.字符流
1) 编码问题
2)认识文本和文本文件
java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte ...的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
3)字符流(Reader Writer)---->操作的是文本文件
字符的处理,一次处理一个字符
字符的底层任然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
// TODO Auto-generated method stub
// israndw.fileReaderandfileWriter();
israndw.BufferedReaderAndBufferedWriterAndPrintWriter();
}
}
1) 编码问题
2)认识文本和文本文件
java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte ...的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
3)字符流(Reader Writer)---->操作的是文本文件
字符的处理,一次处理一个字符
字符的底层任然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
FileReader/FileWriter
public class israndw {
/**
* 把字节流转换成字符流InputStreamReader, OutputStreamWriter为(Reader和Writer抽象类的实现类)
* @param args
* @throws IOException
* @throws IOException
*/
public static void FileInputStreamandOutputStreamWriter() throws IOException{
File file =new File("E:\\HQL 基础.txt");
FileInputStream fis=new FileInputStream(file);
InputStreamReader isr=new InputStreamReader(fis);
OutputStreamWriter osw=new OutputStreamWriter(
new FileOutputStream(new File("E:\\HQL 基础2.txt")));
char [] buf=new char[8*1024];
int b;
while((b=isr.read(buf,0,buf.length))!=-1){
//把buf变成String 从0到b的位置 复制到s里面
String s=new String(buf,0,b);
//System.out.println(s.toString());
System.out.println(s);
osw.write(buf,0,b);
osw.flush();
}
osw.close();
isr.close();
}
/**
* FileReader 和 FileWriter 是Reader和Writer的实现类
* FileReader 和 FileWriter比InputStreamReader 和OutputStreamWriter构造更简单
* 但是只有两个构造方法 不能指定编码方式 所以容易造成乱码
* @author liu
*
*/
public static void fileReaderandfileWriter() throws IOException{
FileReader fr=new FileReader("E:\\Hql.txt");
FileWriter fw=new FileWriter("E:\\hql2.txt");
int k;
char[] c=new char[2048];
while((k=fr.read(c,0,c.length))!=-1){
fw.write(c,0,k);
fw.flush();
}
fw.close();
fr.close();
}
}
======================================================================
字符流的过滤器
BufferedReader ---->readLine 一次读一行
BufferedWriter/PrintWriter ---->写一行
public class test{
/**字符流的过滤器
* 一次读一行 比InputStreamReader, OutputStreamWriter更强大
* 一般BufferedReader和PrintWriter搭配着使用
* @throws IOException
*/
public static void BufferedReaderAndBufferedWriterAndPrintWriter() throws IOException{
BufferedReader br=new BufferedReader(
new InputStreamReader(
new FileInputStream("demo\\out.dat"),"gbk"));
// BufferedWriter bw=new BufferedWriter(
// new OutputStreamWriter(
// new FileOutputStream("demo\\out2.dat")));
PrintWriter pw=new PrintWriter("demo\\out3.dat");
String b;
while((b=br.readLine())!=null){
System.out.println(b);//一次读一行 并不能识别换行
// bw.write(b);
// bw.newLine();//换行
// bw.flush();
pw.println(b);
pw.flush();
}
// bw.close();
pw.close();
}
public static void main(String[] args) throws IOException {// TODO Auto-generated method stub
// israndw.fileReaderandfileWriter();
israndw.BufferedReaderAndBufferedWriterAndPrintWriter();
}
}