1、FileOutputStream :文件字节输出流
java.io.FileOutputStream extends OutputStream
java.io.OutputStream:字节输出流,是一个抽象类,是所有字节输出流的超类。
构造方法的作用:
(1)创建一个 FileOutputStream
(2)根据构造方法中的文件或文件路径,创建一个空文件;
(3)将创建好的 FileOutputStream
文件字节流的使用步骤:
(1)创建一个FileOutputStream对象,在构造方法中传入写入数据的目的地;
(2)调用FileOutputStream对象的write()方法,写入数据;
(3)调用close()方法,释放资源。
public class Test {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("a.txt"));
//write(byte b):写入一个字节
fos.write(97); //a
//write(byte[] b):写入一个字节数组
byte[] bytes = {98,99,100};//bcd
fos.write(bytes);
//write(byte[] b,int off,int len)
byte[] bytes1 = {101,102,103,104,105};
fos.write(bytes1,0,3);//efg
//关闭流,释放资源
fos.close();
}
}
追加/续写,使用带两个参数的构造方法:
FileOutputStream(String name,boolean append)
FileOutputSream(File file,boolean append)
boolean append: 表示是否追加
true:创建对象不会覆盖源文件,继续在文件末尾追加
false:创建新的文件,覆盖源文件
以下代码,在上述基础上继续往a.txt中添加数据。
public class Test01 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("a.txt"),true);
fos.write(new byte[]{107,108,109,110});//klmn
//关闭流,释放资源
fos.close();
}
}
使用文件字节流,往文件中写入字符的方法:需要调用String类中的方法,将字符串转换为字节数组。
public class Test02 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(new File("a.txt"),true);
//像文件中写入换行符
fos.write("\r\n".getBytes());
//将字符串转换为字节数组写入文件
fos.write("hello".getBytes());
//关闭流,释放资源
fos.close();
}
}
注意:任意的文本编辑器(记事本、notepad++、....)在打开文件时,都会查询编码表,将字节转换为字符表示。
0 ~ 127:查询ASCII表
其他:查询系统默认码表(中文系统GBK)
2、FileInputStream:文件字节输入流
java.io.FileInputStream extends InputStream
构造方法的作用:
(1)创建一个FileInputStream对象;
(2)将FileInputStream对象指向构造方法中要读取的文件。
字节输入流的使用步骤:
(1)创建FileInputStream对象,构造方法中绑定要读取的数据;
(2)使用FileInputStream对象中的read()方法,读文件;
(3)调用close(),释放资源。
读数据的方法:
int read():一次读取一个字节,读取到文件末尾,返回-1;
举例,读取上述a.txt文件:
public class Test02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("a.txt"));
int len = 0;
while ((len=fis.read())!=-1){
System.out.print((char)len);
}
}
}
int read(byte[] b):一次读取多个字节,从输入流中读取一定数量的字节,并将其存储在缓冲区的数组b中。
该方法的作用:(1)起到缓冲的作用,存储每次读取到的多个字节;
(2)数组的长度一般定义为1024,或其整数倍。
返回值表示,每次读取到的有效字节数。
一次读取多个字节,要使用String类的构造方法:
举例,读取上述a.txt文件:
public class Test02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("a.txt"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len=fis.read(bytes))!=-1){
System.out.print(new String(bytes,0,len));
}
}
}