Reader
1.read() 方法,只读取单个字符,而且会自动往下读。
返回:作为整数读取的字符,范围在 0 到 65535 之间 ( 0x00-0xffff),如果已到达流的末尾,则返回 -1
2.read(char[] cbuf) 将字符读入数组。
参数:cbuf - 目标缓冲区
返回:读取的字符数,如果已到达流的末尾,则返回 -1
PS:局部变量都要初始化一下。
字节流
3.基类:OutputStream InputStream
使用FileOutputStream 的write(byte[] b) 方法后,不需要调用再调用flush()方法来刷新流。
用字节流读取文件内容和写入文件内容:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class OutputStreamTest {
public static void main(String[] args) {
OutputStreamTest opst = new OutputStreamTest();
opst.readFile();
}
public void readFile() {
FileInputStream fis = null;
try{
fis = new FileInputStream("F:\\demo\\inputDemo.txt");
int len = fis.available();
// 小心,数据太大,内存会溢出
byte[] buff = new byte[len];
fis.read(buff);
System.out.println(new String(buff, 0, len));
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("F:\\demo\\outDemo.txt");
fos.write("abc".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(null != fos)
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}