IO流原理及流的分类
IO流原理
流的分类
InputStream:字节输入流
演示读取文件
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
public class FileinputStream {
public static void main(String[] args) {
}
/**
* 演示读取文件...
* 单个字节的读取,效率比较低
* - >使用 read(byte[] b)
*/
@Test
public void readFile01(){
String filePath = "e:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据.如果没有输入可用,此方法将阻止.
//如果返回-1, 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char) readData); //装成char显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流, 释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 使用 read(byte[] b) 读取文件,提高效率
*/
@Test
public void readFile02(){
String filePath = "e:\\hello.txt";
//字节数组
byte[] buf = new byte[8]; //一次读取8个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多b.length字节的数据到字节数组, 此方法将阻塞,直到某些输入
//如果返回-1, 表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf,0,readLen)); //显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流, 释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream字节输出流
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStream01 {
public static void main(String[] args) {
}
/**
* 演示使用FileOutputStream 将数据写到文件中,
* 如果该文件不存在,则创建该文件
*/
@Test
public void writeFile(){
//创建 FileOutputStream对象
String filePath = "e:\\hello.txt";
FileOutputStream fileOutputStream = null;
try {
//说明
//1. new FileOutputStream(filePath) 创建方式,当写入内容时,会覆盖原来的内容
//2. new FileOutputStream(filePath, true) 创建方式,当写入内容时, 是追加到文件后面
// fileOutputStream = new FileOutputStream(filePath);
fileOutputStream = new FileOutputStream(filePath,true);
//写入一个字节
// fileOutputStream.write('H');
//写入字符串
String str = "wxr,world!";
//str.getBytes() 可以把 字符串 转为 字节数组
// fileOutputStream.write(str.getBytes());
/*
write(byte[] b, int off, int len) 将len字节从位于偏移量 off 的指定字节数组写入到此文件输出流
*/
fileOutputStream.write(str.getBytes(),0,3);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}