1)认识文本和文本文件
java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte ...的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
2)字符流(Reader Writer)---->操作的是文本文件
字符的处理,一次处理一个字符
字符的底层仍然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
字符流的过滤器
BufferedReader ---->readLine 一次读一行
java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
文件是byte byte byte ...的数据序列
文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
2)字符流(Reader Writer)---->操作的是文本文件
字符的处理,一次处理一个字符
字符的底层仍然是基本的字节序列
字符流的基本实现
InputStreamReader 完成byte流解析为char流,按照编码解析
OutputStreamWriter 提供char流到byte流,按照编码处理
例子:
public static void main(String[] args)throws IOException {
FileInputStream in = new FileInputStream("e:\\javaio\\imoocutf8.txt");
InputStreamReader isr = new InputStreamReader(in,"utf-8");//默认项目的编码,操作的时候,要写文件本身的编码格式
FileOutputStream out = new FileOutputStream("e:\\javaio\\imoocutf81.txt");
OutputStreamWriter osw = new OutputStreamWriter(out,"utf-8");
//第一种方法
/*int c ;
while((c = isr.read())!=-1){
System.out.print((char)c);
}*/
//第二种方法
char[] buffer = new char[8*1024];
int c;
/*批量读取,放入buffer这个字符数组,从第0个位置开始放置,最多放buffer.length个
返回的是读到的字符的个数
*/
while(( c = isr.read(buffer,0,buffer.length))!=-1){
String s = new String(buffer,0,c);
System.out.print(s);
osw.write(buffer,0,c);
osw.flush();
}
isr.close();
osw.close();
}
FileReader/FileWriter
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("e:\\javaio\\imooc.txt");
FileWriter fw = new FileWriter("e:\\javaio\\imooc2.txt");
//FileWriter fw = new FileWriter("e:\\javaio\\imooc2.txt",true);
char[] buffer = new char[2056];
int c ;
while((c = fr.read(buffer,0,buffer.length))!=-1){
fw.write(buffer,0,c);
fw.flush();
}
fr.close();
fw.close();
}
字符流的过滤器
BufferedReader ---->readLine 一次读一行
BufferedWriter/PrintWriter ---->写一行
public static void main(String[] args) throws IOException{
//对文件进行读写操作
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("e:\\javaio\\imooc.txt")));
/*BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("e:\\javaio\\imooc3.txt")));*/
PrintWriter pw = new PrintWriter("e:\\javaio\\imooc4.txt");
//PrintWriter pw1 = new PrintWriter(outputStream,boolean autoFlush);
String line ;
while((line = br.readLine())!=null){
System.out.println(line);//一次读一行,并不能识别换行
/*bw.write(line);
//单独写出换行操作
bw.newLine();//换行操作
bw.flush();*/
pw.println(line);
pw.flush();
}
br.close();
//bw.close();
pw.close();
}