public class OutputDemo1 {
public static void main(String[] args) throws IOException {
//1.创建字节输出流的对象 --- 告诉虚拟机我要往哪个文件中写数据了
FileOutputStream fos = new FileOutputStream("D:\\a.txt");
//FileOutputStream fos = new FileOutputStream(new File("D:\\a.txt"));
//2,写数据
fos.write(97);
//3,释放资源
fos.close();//每次使用完流必须要释放资源。
}
}
4、字节流注意事项
5、字节流一次写多个数据
第2、3种就是一次写多个数据
public class OutputDemo4 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("bytestream\\a.txt");
//一次写一个数组;作者:编程ID
/\*byte [] bys = {97,98,99};
fos.write(bys);\*/
byte [] bys = {97,98,99,100,101,102,103};
fos.write(bys,1,2);//从bys数组第一个索引开始写两个
fos.close();//每次使用完流必须要释放资源。
}
}
6、字节流-两个问题
public class OutputDemo5 {
public static void main(String[] args) throws IOException {
//第二个参数就是续写开关,如果没有传递,默认就是false,
//表示不打开续写功能,那么创建对象的这行代码会清空文件.
//如果第二个参数为true,表示打开续写功能
//那么创建对象的这行代码不会清空文件.
FileOutputStream fos = new FileOutputStream("C:KuGou\\a.txt",true);
fos.write(97);
//能加一个换行
fos.write("\r\n".getBytes());
fos.write(98);
//能加一个换行
fos.write("\r\n".getBytes());
fos.write(99);
//能加一个换行
fos.write("\r\n".getBytes());
fos.write(100);
//能加一个换行
fos.write("\r\n".getBytes());
fos.write(101);
//能加一个换行
fos.write("\r\n".getBytes());
fos.close();
}
}
7、字节流-trycatch捕获异常
public class OutputDemo6 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
//System.out.println(2/0);
fos = new FileOutputStream("C:KuGou\\a.txt");
fos.write(97);
}catch(IOException e){
e.printStackTrace();
}finally {
//finally语句里面的代码,一定会被执行.
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
8、字节流小结
9、字节流输入流
public class OutputDemo7 {
public static void main(String[] args) throws IOException {
//如果文件存在,那么就不会报错.
//如果文件不存在,那么就直接报错.
FileInputStream fis = new FileInputStream("C:KuGou\\a.txt");
int read = fis.read();
//一次读取一个字节,返回值就是本次读到的那个字节数据.
//也就是字符在码表中对应的那个数字.
//如果我们想要看到的是字符数据,那么一定要强转成char
System.out.println((char)read);
//释放资源
fis.close();
}
}
10、字节流读多个字节
public class OutputDemo8 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("C:\\KuGou\\a.txt");
//1,文件中多个字节我怎么办?
/\*while(true){
int i1 = fis.read();
System.out.println(i1);
}\*/
int b;
while ((b = fis.read())!=-1){
System.out.println((char) b);
}
fis.close();
}
### 最后
总的来说,面试官要是考察思路就会从你实际做过的项目入手,考察你实际编码能力,就会让你在电脑敲代码,看你用什么编辑器、插件、编码习惯等。所以我们在回答面试官问题时,有一个清晰的逻辑思路,清楚知道自己在和面试官说项目说技术时的话就好了
![](https://img-blog.csdnimg.cn/img_convert/db46a4578d859d11d727cc5a03690685.webp?x-oss-process=image/format,png)
![](https://img-blog.csdnimg.cn/img_convert/f516b4ec446def11edf7bd468b8f242c.webp?x-oss-process=image/format,png)
是考察思路就会从你实际做过的项目入手,考察你实际编码能力,就会让你在电脑敲代码,看你用什么编辑器、插件、编码习惯等。所以我们在回答面试官问题时,有一个清晰的逻辑思路,清楚知道自己在和面试官说项目说技术时的话就好了
[外链图片转存中...(img-q0E14mwZ-1718013385496)]
[外链图片转存中...(img-9iGAlMxi-1718013385497)]