关于FileOutputStream



今天做题目的时候看见FileOutputStream,顺带巩固一下输入和输出流

package cn.com.bochy.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class test2 {
public static void main(String[] args) {
//创建文件对象
File file = new File("D:/"," hellow.txt");
//如果文件不存在
if(! file.exists()){
try {
//创建该文件
file.createNewFile();
System.out.println("文件已创建");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//创建FileOutputStream对象
FileOutputStream outputStream = new FileOutputStream(file);
//创建byte型数组
byte [] bs = "我有一只小毛驴,我从来也不骑".getBytes();
//将数组的信息写到文件中
outputStream.write(bs);
//关闭流
outputStream.close();
//创建FileInputStream类对象
FileInputStream inputStream = new FileInputStream(file);
//创建byte数组
byte [] bs2 = new byte[1024];
//从文件中读取信息
int i = inputStream.read(bs2);
//输出文件中的信息
System.out.println(new String(bs2,0,i));
//关闭流
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


你可能感兴趣的:(java学习)