一、字节流
用于以字节的形式读取和写入数据
InputStream字节输入流
public static void main(String[] args) {
try {
//准备文件file_1.txt其中的内容是AB,对应的ASCII分别是65 66
File f =new File("d:/develop/file_1.txt");
//创建基于文件的输入流
FileInputStream fis =new FileInputStream(f);
//创建字节数组,其长度就是文件的长度
byte[] all =new byte[(int) f.length()];
//以字节流的形式读取文件所有内容
fis.read(all);
for (byte b : all) {
//打印出来是65 66
System.out.println(b);
}
//每次使用完流,都应该进行关闭
fis.close();
} catch (IOException e)
e.printStackTrace();
}
OutputStream字节输出流
public static void main(String[] args) {
try {
// 准备文件file_2.txt其中的内容是空的
File f = new File("d:/develop/file_2.txt");
// 准备长度是2的字节数组88,89,其对应的字符分别是X,Y
byte data[] = { 88, 89 };
// 创建基于文件的输出流
FileOutputStream fos = new FileOutputStream(f);
// 把数据写入到输出流
fos.write(data);
// 关闭输出流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这样传入数据得需要ASCII码表的借助,较为麻烦;
二、字符流
专门用于字符的形式读取和写入数据
Reader字符输入流
public static void main(String[] args) {
// 准备文件file_1.txt其中的内容是AB
File f = new File("d:/develop/file_1.txt");
// 创建基于文件的Reader
try (FileReader fr = new FileReader(f)) {
// 创建字符数组,其长度就是文件的长度
char[] all = new char[(int) f.length()];
// 以字符流的形式读取文件所有内容
fr.read(all);
for (char b : all) {
// 打印出来是A B
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Writer字符输出流
public static void main(String[] args) {
// 准备文件file_2.txt
File f = new File("d:/file_2.txt");
// 创建基于文件的Writer
try (FileWriter fr = new FileWriter(f)) {
// 以字符流的形式把数据写入到文件中
String data="abcdefg1234567890";
fr.write(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}