java高级特性之输出流
输出流
输出流:是向文件里写入内容
注意:写入文件合读取文件 都需要创建特定的方法来指向读取文件的位置
字节输出流 OutputStream
FileOutputStream f = new FileOutputStream(“文件路径”)
方法:
方法 | 说明 |
---|---|
.getBytes () | 获取到输出的文字 |
.write(): 写入文件 三个参数:变量名字 开始的位置 结束的位置
代码演示:
public static void main(String[] args) {
FileOutputStream fos = null;
try {
//创建FileOutputStream对象
fos = new FileOutputStream ( "E:\\java高级特性\\aaa.txt",true );
//输出的文字
String str = "好好学习java";
//转换成byte字节的数组
byte[] words = str.getBytes ();//获取到
//开始写入文本
fos.write ( words,0,words.length );//变量名字 开始的位置 长度
System.out.println ("文件已更新");
} catch (IOException e) {
e.printStackTrace ( );
} finally {
try {
//关闭流
fos.close ();
} catch (IOException e) {
e.printStackTrace ( );
}
}
}
字符输出流 Writer
-
使用FileWriter类与BufferedWriter类
- BufferedWriter类是Writer类的子类
方法
方法 | 说明 |
---|---|
.newLine () | 换行 |
.write() | 写入文件的方法 |
.fiush() | 刷新缓冲区 |
代码演示:
public static void main(String[] args) {
FileWriter fw = null;
BufferedWriter bfw = null;
try {
//创建FileWriter对象
fw = new FileWriter ( "E:\\java高级特性\\aaa.txt" );
//创建BufferedWriter对象
bfw = new BufferedWriter ( fw );
bfw.write ( "大家好" );
bfw.write ( "我是栗志青" );
bfw.write ( "是个大帅哥" );
bfw.newLine ();//换行的作用
bfw.write ( "正在学习javaIO流" );
bfw.flush ();//刷新
} catch (IOException e) {
e.printStackTrace ( );
} finally {
try {
fw.close ();
bfw.close ();
} catch (IOException e) {
e.printStackTrace ( );
}
}
}
注意:只用FileWriter类就不用创建BufferedWriter类就用不了换行的方法
代码演示:
public static void main(String[] args) {
FileWriter fw = null;
try {
//创建一个FileWriter文件
fw = new FileWriter ( "E:\\java高级特性\\aaa.txt" );
fw.write ( "栗志青真帅" );//写入的内容
fw.flush ();//刷新缓冲区
System.out.println ("写入成功");
} catch (IOException e) {
e.printStackTrace ( );
} finally {
//关闭
try {
fw.close ();
} catch (IOException e) {
e.printStackTrace ( );
}
}
}
读写二进制文件
-
DataInputStream类
- FileInputStream的子类
- 与FileInputStream类结合使用读取二进制文件 DataOutputStream类
- FileOutputStream的子类
- 与FileOutputStream类结合使用写二进制文件
代码演示:
//读取到二进制文件之后,便写入一个新的二进制文件
public static void main(String[] args) {
FileInputStream fis = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
//创建输入流对象 先读取到这个文件
fis = new FileInputStream ( "E:\\java高级特性\\栗志青.jpg" );
dis = new DataInputStream ( fis );
//输出流对象 然后再写入这个文件
fos = new FileOutputStream ( "E:\\java高级特性\\青青.jpg" );
dos = new DataOutputStream ( fos );
//开始读写
int temp;
while ((temp = dis.read ( )) != -1) {//读写到的这个文件赋值给temp然后判断等于-1的话就是没有了
dos.write ( temp );//然后把temp写入到那个文件里
}
} catch (IOException e) {
e.printStackTrace ( );
} finally {
//关闭
try {
if (fis != null) {
fis.close ( );
}
if (dis != null) {
dis.close ( );
}
if (fos != null) {
fos.close ( );
}
if (dos != null) {
dos.close ( );
}
} catch (IOException e) {
e.printStackTrace ( );
}
}
}