最后一道练习题有点长,。。。
如上图:
new FileInputStream("文件路径"); // 读取二进制文件
new BufferedInputStream(new FileInputStream("文件路径")); // 为了提高FileInputStream的效率
new FileOutputStream("文件路径"); // 写入二进制文件
new BufferedOutputStream(new FileOutputStream("文件路径")); // 为了提高FileOutputStream的效率
// 他们结合在一起,实现文件拷贝(字节,字符)
int len = read(byte[]) ; 返回读到的实际字节数,返回 -1 表示读完了
write(byte[], 0 , 长度);
new FileReader("文件路径"); // 读取文本文件 *.txt *.java *.html *.xml
new BufferedReader(new FileReader("文件路径")); // 提高效率,还可以以行为单位读 readLine()
new FileWriter("文件路径"); // 写入文本文件 *.txt *.java *.html *.xml
new BufferedWriter(new FileWriter("文件路径")); // 提高效率, 有通用换行 newLine()
// 转换流 - 文件编码与idea默认编码不一致时
new InputStreamReader(new FileInputStream("文件路径")); // 读取时,避免编码不一致导致的乱码
new OutputStreamWriter(new FileOutputStream("文件路径")); // 写入时,避免乱码
int len = read(char[]) ; 返回读到的实际字符数,返回 -1 表示读完了
String line = readLine(); 返回读取的一行数据,返回 null 表示读完了
write(String )
案例
需求:使用字节缓冲流反复读取数据
public class TestBufferedInputStream {
public static void main(String[] args) throws IOException {
// FileInputStream in = new FileInputStream("a.txt");
BufferedInputStream in = new BufferedInputStream(new FileInputStream("a.txt"));
in.mark(1024); // 做一个标记
read6(in);
in.reset(); // 回到上次做标记的位置
read6(in);
}
private static void read6(InputStream in) throws IOException {
System.out.println("=================read===============");
System.out.println(in.read());
System.out.println(in.read());
System.out.println(in.read());
System.out.println(in.read());
System.out.println(in.read());
System.out.println(in.read());
}
}
需求 字符流
a.txt 读入进来
床前明月光
疑是地上霜
举头望明月
低头思故乡
颠倒后写出到新文件 b.txt
光月明前床
...
...
public class TestPoem {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("a.txt");
FileWriter writer = new FileWriter("b.txt");
char[] buf = new char[1024];
int len = reader.read(buf); // 返回值是实际读取的字符数
String str = new String(buf, 0, len);
// System.out.println(str);
// \r\n
String[] split = str.split("\r\n");
for (String s : split) {
// 根据其中一行创建 stringBuilder 对象
// System.out.println(new StringBuilder(s).reverse());
writer.write(new StringBuilder(s).reverse().toString());
writer.write("\r\n");
}
writer.close();
}
}
字符缓冲流对刚才练习改写:
public class TestPoem2 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
BufferedWriter writer = new BufferedWriter