字节流写数据的两个常用构造方法:
FileOutputStream(String name)
创建文件输出流以指定的名称写入文件。
FileOutputStream(File file)
创建文件输出流以写入由指定的File
对象表示的文件
先说结论:通过分析源码可知,两者的实现是一样的,下面给出示例。
根据第一个构造方法的源码:
public FileOutputStream(String name) throws FileNotFoundException { this(name != null ? new File(name) : null, false); }
在名字不为null时,会new file(name),也就是生产一个file对象:
FileOutputStream fos = new FileOutputStream(new File("myFile\\fos.txt"));
那么使用第二个构造方法时,我们需要先创建一个File对象,在把这个File对象作为参数。
// FileOutputStream(File file)创建文件输出流以写入由指定的 File对象表示的文件 File f1 = new File("myFile\\fos.txt"); FileOutputStream fos1 = new FileOutputStream(f1);
上面的代码也就等同于:
FileOutputStream fos1 = new FileOutputStream(new File("myFile\\fos.txt"));
由此可见,在使用两者是,使用第一种更方便。
关于字节流写数据的三种方式的演示:
以此段代码作为基本结构
public class FileOutputStreamDemo { public static void main(String[] args) throws IOException { //FileOutputStream(String name)创建文件输出流以指定的名称写入文件。 FileOutputStream fos = new FileOutputStream("myFile\\fos.txt"); /* public FileOutputStream(String name) throws FileNotFoundException { this(name != null ? new File(name) : null, false); } */ // 1.void write(int b) 将指定的字节写入此文件输出流。 fos.write(97); fos.write(98); fos.write(99); fos.write(100); fos.write(101); } }
运行结果:
两者是同一个结果
//2.void write(byte[] b) 将 b.length个字节从指定的字节数组写入此文件输出流。 byte[] bys = {102,103,104,105,106}; fos.write(bys); //使用更方便的字符数组生成方式 //byte[] getBytes() 使用平台的默认字符集将此 String编码为字节序列,将结果存储到新的字节数组中。 byte[] bys = "fghij".getBytes();
fos.write(bys)
运行结果:
byte[] bys = "klmno".getBytes(); //3.void write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。 // fos.write(bys,0,bys.length); //结果:klmno fos.write(bys,1,3); //结果:lmn
最后不要忘记释放资源:
fos.close();
原文:https://www.cnblogs.com/pxy-1999/p/12703281.html