package com.bjpowernode.demo01;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* FileOutputStream字节输出流
* @author Administrator
*
*/
public class Test06 {
public static void main(String[] args) throws IOException {
// 1)建立流通道
//如果文件不存在,系统会创建新的文件, 如果文件已存在, 会覆盖文件原来的内容
// FileOutputStream fos = new FileOutputStream("d:/def.txt");
//如果文件不存在就创建文件, 如果文件已存在,在追加的方式打开 , 新写入的内容追加到文件的后面
FileOutputStream fos = new FileOutputStream("d:/def.txt" , true );
//2)写数据
//一次写一个字节
fos.write(65);
//一次写一个字节数组
byte[] bytes = "hello".getBytes();
fos.write(bytes);
//可以把字节数组中的部分字节写到输出流中
bytes = "welcome to qingdao".getBytes();
fos.write(bytes, 10, 5); //把bytes字节数组从10开始的5个字节写到输出流中
//3)关闭流通道
fos.close();
}
}
package com.bjpowernode.demo01;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 字节输出流的异常处理
* @author Administrator
*
*/
public class Test07 {
public static void main(String[] args) {
// m1(); //手动关闭流, 异常处理
m2(); //自动关闭流, 异常处理
}
private static void m2() {
try (
FileOutputStream fos = new FileOutputStream("d:/def.txt", true);
){
fos.write(65);
fos.write(66);
fos.write(67);
fos.write( "hello".getBytes() );
} catch (Exception e) {
}
}
private static void m1() {
FileOutputStream fos = null ;
try {
fos = new FileOutputStream("d:/def.txt");
fos.write(65);
fos.write(66);
fos.write(67);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null ) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
以下是文件复制:
package com.bjpowernode.demo01;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 文件复制
* @author Administrator
*
*/
public class Test08 {
public static void main(String[] args) {
String srcFile = "D:\\course\\03-JavaSE\\video\\JavaSE-084以字节数组为单位读取.avi";
String destFile = "d:/hehe.avi";
copyFile(srcFile, destFile);
}
//一次复制一个字节数组, 自动关闭流, 异常处理
public static void copyFile(String srcFilename, String destFilename) {
try (
FileInputStream fis = new FileInputStream(srcFilename);
FileOutputStream fos = new FileOutputStream(destFilename);
){
byte [] bytes = new byte[1024];
int len = fis.read(bytes);
while( len != -1 ){
//把读到的字节都写到输出流中
fos.write(bytes, 0, len);
len = fis.read(bytes);
}
} catch (Exception e) {
}
}
//按字节进行文件复制
public static void copyFile2(String srcfilename, String destFileName) {
FileInputStream fis = null;
FileOutputStream fos = null ;
try {
fis = new FileInputStream(srcfilename);
fos = new FileOutputStream(destFileName);
int cc = fis.read();
while( cc != -1 ){
//对读到的字节cc进行处理, 把cc写到输出流中
fos.write(cc);
cc = fis.read(); //读下个字节
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if ( fis != null ) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null ) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}