JavaSE-17.3.2【字节流常用的构造方法和写数据的三种方式】

2021/6/5 12:22:30

本文主要是介绍JavaSE-17.3.2【字节流常用的构造方法和写数据的三种方式】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 1 package day8.lesson3;
 2 
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 
 8 /*
 9 3.3 字节流常用的构造方法和写数据的三种方式
10 
11     构造方法
12         FileOutputStream(String name)
13         FileOutputStream(File file)
14 
15     写数据的三种方式
16         void write(int b)
17             将指定的字节写入此文件输出流,一次写一个字节数据
18         void write(byte[] b)
19             将b.length字节从指定的字节数组写入此文件输出流,一次写一个字节数组数据
20         void write(byte[] b, int off, int len)
21             将len字节从指定的字节数组开始,从偏移量off(索引)开始写入此文件输出流,一次写一个字节数组的部分数据
22  */
23 public class FileOutputStreamDemo02 {
24     public static void main(String[] args) throws IOException {
25         FileOutputStream fos = new FileOutputStream("stage2\\src\\day8\\lesson3\\fos2.txt");
26         /*
27         public FileOutputStream(String name) throws FileNotFoundException {
28             this(name != null ? new File(name) : null, false);
29         }
30         即文件已存在时不会再重新创建文件
31          */
32 
33         /*File file = new File("stage2\\src\\day8\\lesson3\\fos2.txt");
34         FileOutputStream fos2 = new FileOutputStream(file);
35 //        FileOutputStream fos2 = new FileOutputStream(new File("stage2\\src\\day8\\lesson3\\fos2.txt"));
36         //该构造方法实质与第一种构造方法的内部实现相同
37         fos2.close();*/
38 
39         //写入方式1
40         fos.write(97);
41         fos.write(98);
42         fos.write(99);
43         fos.write(100);
44         fos.write(101);
45         //'a' 'b' 'c' 'd' 'e'
46 
47         //写入方式2
48         byte[] bytes = {102, 103, 104};
49         fos.write(bytes); //'f' 'g' 'h';既然是数组,也可以理解为"fgh"
50 
51         //PS:str.getBytes()返回字符串对应的字节数组
52         byte[] bytes1 = "ABCDEF".getBytes();
53         fos.write(bytes1);
54 
55         //写入方式3
56         fos.write(bytes1, 0, bytes1.length);
57         fos.write(bytes1, 1, 3);
58 
59         fos.close();
60     }
61 }

 



这篇关于JavaSE-17.3.2【字节流常用的构造方法和写数据的三种方式】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程