IO流
一、IO流的分类:
1、根据流的方向:
①输入流:读取
②输出流:写入
2、根据操作文件的类型:
①字节流:适用于所有类型的文件
②字符流:使用于纯文本文件
二、字节输出流
1、write方法的重载:
①write(int b)
②write(byte[] b)
③write(byte[] b, int off, int len)
2、换行与续写
①换行:Windows中:\r\n
Linux中:\n
Max中:\r
public class Test1 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("day26-code\\aaa\\a.txt");
byte[] b1 = "woshidashuaige".getBytes();
fos.write(b1);
byte[] b2 = "\r\n".getBytes();
fos.write(b2);
byte[] b3 = "niyeshi".getBytes();
fos.write(b3);
fos.close();
}
}
②续写:
FileOutputStream fos = new FileOutputStream("day26-code\\aaa\\a.txt", true);
三、字节输入流
1、循环读取数据
public class Test2 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("day26-code\\aaa\\a.txt");
int b;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
fis.close();
}
}
2、拷贝数据
public class Test3 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("day26-code\\aaa\\a.txt");
FileOutputStream fos = new FileOutputStream("day26-code\\aaa\\b.txt");
int b;
while ((b = fis.read()) != -1) {
fos.write(b);
}
fos.close();
fis.close();
}
}
3、拷贝数据缓冲池优化
public class Test4 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("day26-code\\aaa\\a.txt");
FileOutputStream fos = new FileOutputStream("day26-code\\aaa\\b.txt");
int len;
/*使用数组缓冲,加快传输速度*/
byte[] bytes = new byte[8];
/*判断条件还是不等于-1
* len表示的是这次read改变了缓冲池bytes中多少长度*/
while ((len = fis.read(bytes)) != -1) {
/*只写入改变了的元素
* 解释:可能最后一次读取,缓冲池并未被完全覆盖,只有前面几个元素被覆盖
* 此时,被改变的元素个数赋值给了len,根据len的大小进行写可以保证写无误*/
fos.write(bytes, 0, len);
}
fos.close();
fis.close();
}
}
4、不同版本JDK通过try——catch处理异常
四、字符集
1、GBK编码
2、Unicode编码
UTF-8是Unicode字符集的一种编码方式,并非是字符集,注意区分
3、如何避免乱码
4、编码与解码
五、字符输入流
public class Test5 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("day26-code\\aaa\\a.txt");
int ch;
/*字符流一次读入一个字符,但是是用十进制整数表示的编码*/
while ((ch = fr.read()) != -1) {
/*通过强转,显示字符编码表示的内容*/
System.out.print((char) ch);
}
fr.close();
}
}
public class Test5 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("day26-code\\aaa\\a.txt");
int len;
/*改进,使用数组缓冲池
* 注意和字节流的区别:这里用的是char数组,那边是byte数组*/
char[] chars = new char[8];
while ((len = fr.read(chars)) != -1) {
System.out.print(new String(chars, 0, len));
}
fr.close();
}
}
注意改进的方法里,read带参,通过数组默认进行了强转操作
六、字符输出流
1、方法
public class Test6 {
public static void main(String[] args) throws IOException {
// FileWriter fw = new FileWriter("day26-code\\aaa\\b.txt");
FileWriter fw = new FileWriter("day26-code\\aaa\\b.txt", true);
fw.write("\r\n");
fw.write("你也是一只猪!");
fw.close();
}
}