ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2021-06-05 11:01:38  阅读:189  来源: 互联网

标签:字节 构造方法 fos write 17.3 FileOutputStream new JavaSE fos2


 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 }

 

标签:字节,构造方法,fos,write,17.3,FileOutputStream,new,JavaSE,fos2
来源: https://www.cnblogs.com/yppah/p/14852241.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有