1 . 追加的方式和覆盖的方式要清楚怎么去写 true 追加 false 覆盖
2 . 重点看while的条件和方法体
3 . 首先用文件字节流实现(下面有用文件字符流实现的)
package com.qf.demo3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 赋值文件
* 1 创建流对象
* 2 读
* 3 写
* 4 关流
*/
public class Test3 {
public static void main(String[] args) {
// 1 创建流对象
FileInputStream fis = null;
FileOutputStream fos =null;
try {
fis = new FileInputStream(new File("abc.txt"));
fos = new FileOutputStream(new File("aaa.txt"),true);// boolean append true 追加 false 覆盖
// 2 读
byte[] bs = new byte[10];
int num = 0;
while((num = fis.read(bs))!=-1){
// 3 写
fos.write(bs,0,num);
fos.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
4 . 用文件字符流实现
package com.qf.demo4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 1 创建流对象
* 2 读
* 3 写
* 4 关流
* @author Administrator
*
*/
public class Test3 {
public static void main(String[] args) {
// 1 创建流对象
FileReader reader = null;
FileWriter writer =null;
try {
reader = new FileReader(new File("aaa.txt"));
writer = new FileWriter(new File("ccc.txt"));
// 2 读
char[] cs = new char[10];
int num = 0;
while((num = reader.read(cs))!=-1){
// 3 写
writer.write(cs, 0, num);
writer.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(writer!=null){
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}