java对文件的操作是以流的方式进行的,流是java内存中一段有序数据序列。
1.按照流的流向方向分为,输入流和输出流,方向的参照物为程序。
2.按照流的处理单位又分为字节流和字符流,字节流读取的最小的单位为字节(1byte);字符流读取的最小单位为字符(1char = 2byte),占2个字节。
3.按照功能流分为节点流和处理流。java对文件的读取是采用节点流,FileOutputStream ,FileInoutStream .而处理流是对节点流的封装,BufferedInputStream 使FileInputStream具有了缓冲的功能。
I/O 主要有四个基本的类: InputStream OutputStream Writer Reader
字节流和字符流之间可以转化:
1.字节流转型字符流---- InputStreamReader / OutputStreamWriter两个类可以实现。
2.字符流转向字节流---- 从字符流到字节流:可以从字符流中获取char[]数组,转换为String,然后调用String的API函数getBytes() 获取到byte[],然后就可以通过ByteArrayInputStream、ByteArrayOutputStream来实现到字节流的转换。
<pre name="code" class="java">package IOTest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class IODemo02 {
/**
* 字节流 转换成字符流
* */
public static void main(String[] args) {
String str = null;
String str2 =null;
byte[] b = new byte[1024];
try {
//字节流
InputStream in = new FileInputStream(new File(
"./src/IOTest/test.txt"));
// while(in.read(b)>0){
// str2 = new String(b);
// }
//字符流
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while(reader.read()!=-1){
str = reader.readLine();
}
System.out.println(str);
//System.out.println(str2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package IOTest;
<pre name="code" class="java">import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
public class IODemo {
/**
* 字符流转成字节流
* */
public static void main(String[] args) {
byte[] b = new byte[1024];
String str = null;
try {
// 1.读取文件
BufferedReader bReader = new BufferedReader(new FileReader(
"./src/IOTest/test.txt"));
while (bReader.read() != -1) {
str = bReader.readLine();// 2.读取结果放到字符串
System.out.println(str);
}
if (str != null) {
b = str.getBytes("UTF-8");// 3.将字符串内容放到字节数组中
ByteArrayInputStream bin = new ByteArrayInputStream(b);
System.out.println(bin);//4.转成了字节流
}
} catch (Exception e) {
e.printStackTrace();
}
}
}