IO字符流
1.字符流是什么
字符流是可以直接读写字符的IO流
字符流读取字符,就要先读取到字节数据,然后转为字符,如果要写出字符,需要把字符转为字节在写。
2.FileReader
FileReader类的read()方法可以按照字符大小读取
package com.heima.stream;
import java.io.FileIReader;
public class Demo_FileIReader {
public static void main(String[] args) {
FileIReader fr = new FileIReader("xxx.txt");
int c);
while((c = fr.read()) != -1) {
System.out.println(x);
}
fr.close();
}
}
3FileWriter
package com.heima.stream;
import java.io.FileWriter;
public class Demo_FileWriter {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("yyy.txt");
fw.writer("大家好,基础班快要接近尾声了,大家要努力,要坚持!!!");
fw.write(97);
fw.close();
}
}
4字符流的拷贝
package com.heima.stream;
import java.io.FileWriter;
public class Demo_Copy {
public static void main(String[] args) throws IOException {
FileIReader fr = new FileIReader("xxx.txt");
FileWriter fw = new FileWriter("zzz.txt");
int c;
while((c = fr.read()) != -1 {
fw.write(c);
}
fr.close();
fw.close(); //Writer类中有一个2k的小缓冲区。不关流,就会将内容写到缓冲区里,关流会将缓冲区内容刷新在关闭
}
}
5将文本反转
package com.heima.test;
public class Test1 {
/**
*注意事项流对象尽量晚开早关
**/
public static void main(String[] args) {
BufferrdReader br = new BufferrdReader(new FileReader("zzz.txt"));
BufferrdWriter bw = new BufferrdWriter(new FileWriter("revzzz.txt"));
ArrayList<String> list = new ArrayList<>();
String line;
while((line = br.readLine()) != null) {
list.add(line);
}
br.close();
BufferrdWriter bw = new BufferrdWriter(new FileWriter("revzzz.txt"));
for(int i = list.size() -1; i >= 0; i--) {
bw.write(list.get(i));
bw.newLine();
}
br.close();
bw.close();
}
}
6LineNumberReader
LineNumberReader是BufferrdReader的子类,具有相同的功能,并且可以统计行号
调用getlineNumber()方法可以获取当前行号
调用getlineNumber()方法可以设置当前行号
public class Demo_LineNumberReader {
public static void main(String[] args) throws IOException {
LineNumberReader Inr = new LineNumberReader(new FileReader("zzz.txt"));
String line;
lnr.setLineNumber(100);
while((line = lnr.readLine()) != nwll) {
System.out.println(lnr.getLineNumber() + ":" + line);
}
lnr.close();
}
}
7码表读写字符
public class Demo_TransIO {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream("utf-8.txt"),"utf-8");//指定码表读字符
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gdk.txt"), "gdk");//指定码表写字符
int c;
while((c = isr.read()) != -1) {
osw.write(c);
}
isr.close();
osw.close();
}
public static void main(String[] args) throws IOException {
//默认编码表读写,出现乱码
FileReader fr = new FileReader(new FileReader("utf-8.txt"));
FileWriter fw = new FileWriter(new FileWriter("gdk.txt"));
int c;
while((c = fr.read()) != -1) {
fw.write(c);
}
fr.close();
fw.close();
}
}