IO(BIO/NIO/AIO) Thread Socket Collection
一、 IO
程序中的所有数据都是用 流 的方式进行传输与保存的
1.1 字节流
字节流操作的是byte类型的数据
1.1.1 InputStream
首先看InputStream的定义
public abstract class InputStream extends Object implements Closeable
- 抽象类
只能读取文件length
public class inTest {
public static void main(String[] args) throws IOException {
File f = new File("data/" + File.separator + "OutTest.txt");
InputStream in = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
in.read(b);
System.out.println(b);
in.close();
}
}
读取文件内容
public static void main(String[] args) throws IOException {
File f = new File("data/" + File.separator + "OutTest.txt");
InputStream in = new FileInputStream(f);
byte[] b = new byte[1024];
int temp = 0;
int len = 0;
while ((temp = in.read())!=-1){//-1 :文件读取完毕的标志
b[len]=(byte) temp;
len++;
}
in.close();
System.out.println(new String(b,0,len));
}
private static void read(){
// 由于fis作用域只在try中,所以应该提前设定为空
FileInputStream fis = null;
try {
FileInputStream fis = new FileInputStream("data/ifengdata.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(null != fis){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}v
}
buffer
try {
FileInputStream fis = new FileInputStream("data/ifengdata.txt");
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != fis.read(length = fis.read(buffer, 0, buffer.length))){
String result = new String(buffer,0,length);
System.out.println(result);
}
1.1.2 OuputStream
OutputStream是整个IO包中字节输出流的最大父类,类定义如下
public abstract class OutputStream extends Object implement Closeable,Flushable
- 抽象类,必须使用实例化的类(FileOutputStream)
- Closeable 可以关闭的操作
- Flushable 刷新,清空内存中的数据
public class outTest {
public static void main(String[] args) throws IOException {
File f = new File("data" + File.separator + "OutTest.txt");
OutputStream out = new FileOutputStream(f);//文件不存在会自动创建
String str = "Test OutputStream";
byte[] b = str.getBytes();
out.write(b);
out.close();
}
也可以一个byte一个byte的输出
for(int i = 0 ; i < b.length ; i ++){
out.writer(b[i]);
}
1.2 字符流
在程序中一个字符等于两个字节,Java提供了Reader、Writer两个专门操作字符流的类
1.2.1 Reader
public abstract class Reader extends Objects implements Readable,Closeable
- 抽象类 ,FileReader
public static void main(String[] args) throws IOException {
File f = new File("data/" + File.separator + "Writer.txt");
Reader input = new FileReader(f);
char[] c = new char[1024];
//
int temp = 0;
int len = 0;
while ((temp = input.read()) != -1){
c[len] = (char) temp;
len ++;
}
input.close();
System.out.println(new String(c));
}
1.2.2 Writer
public abstract class Writer extends Object implement Appendable,Closeable,Flushable
- 抽象类 实例化方法(FileWriter)
public class writerTest {
public static void main(String[] args) throws IOException {
File f = new File("data/" + File.separator + "Wirter.txt");
Writer out = new FileWriter(f);
String str = "Test Writer";
out.write(str);
out.close();
}
}
字节流与字符流的区别
字节流在操作的时候本身不会用到缓冲区(内存)的,是与文件本身直接操作的。
字符流操作的时候使用缓冲区
字节流在操作文件时,即使不close,文件也能输出,
字符流不关闭的话,字符在缓冲区中,可以使用flush方法强制输出