JAVA中的FileOutputStream
- FileOutputStream使用重点:
1、使用方法
2、FileOutputStream构造方法中的append参数
3、写入String字符串的方法
4、强制输出缓存区内剩余数据,清空缓存区
public class FileOutputStreamTest01 {
public static void main(String[] args){
FileOutputStream fos = null;
try {
//第二个参数:append,为true时将以追加的方式在文件末尾写入
fos = new FileOutputStream("src/io/tempOutput.txt",true);
//写入数组的byte是ASCII码,会自动转为对应的字节
byte[] bytes = {100,101,102};
//使用write方法要谨慎,直接write()会将已有的文件清空,再写入数据
//如果没有目标文件,则会新建文件
fos.write(bytes);
//将byte数组一部分写出
fos.write(bytes,0,2);
//写入String字符串
String strings = "我有一只小乌龟!";
//string数据类型转为byte[]数组
byte[] bytes1 = strings.getBytes();
fos.write(bytes1);
//写完之后一定要刷新
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
文件复制
-
使用FileOutputStream和FileInputStream完成文件的复制:
使用该方法拷贝文件时,文件类型随意,所有文件都可拷贝 -
finally处两个close方法要分开写,一起try的话其中一个出现异常,可能会影响到另一个的关闭
public class FileOutputStreamTest02 {
public static void main(String[] args) {
FileInputStream fls = null;
FileOutputStream fos = null;
try {
//指定输入输出的文件
fls = new FileInputStream("src\\readme");
fos = new FileOutputStream("src\\io\\copiedfile.txt");
// //一次复制1KB
byte[] bytes = new byte[1024];
//一次读取的1024个字节转为String时可能会发生拼接错误
// byte[] bytes = new byte[fls.available()];
int readCount;
//边读边写
while ((readCount = fls.read(bytes)) != -1){
fos.write(bytes,0,readCount);
}
//flush
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//分开try,一起try的话其中一个出现异常,可能会影响到另一个的关闭
if (fls != null){
try {
fls.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}