很简洁,具体操作请看API,代码如下:
package file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//TODO Auto-generated method stub
keyboardInput();
fileCopy();
}
/**
* 文件拷贝
* @throws FileNotFoundException
* @throws IOException
*/
public static void fileCopy() throws FileNotFoundException, IOException {
int charsum =0;
int charlong = 0;
File file2 = new File("F:\\copy.txt");
//如果文件存在
if(file2.exists()){
//输入流,用于读文件
FileReader fr = new FileReader(new File("F:\\filetest\\test.txt"));
//输出流,用于写入
FileWriter fw = new FileWriter(file2);
char[] cbuf = new char[1024];//2k的大小
//如没有到文件的结尾继续
while( (charlong = fr.read(cbuf)) !=-1){
fw.write(cbuf,0,charlong);
}
//关闭流
fr.close();
fw.close();
}else{
//如果不存则创建
file2.createNewFile();
}
FileReader fr = new FileReader(new File("F:\\filetest\\test.txt"));
FileWriter fw = new FileWriter(file2);
char[] cbuf = new char[1024];
while( (charlong = fr.read(cbuf)) !=-1){
System.out.println(charlong);
fw.write(cbuf,0,charlong);
}
fr.close();
fw.close();
}
/**
* 键盘录入
* @throws IOException
* @throws FileNotFoundException
*/
public static void keyboardInput() throws IOException,
FileNotFoundException {
File file = new File("F:\\filetest\\test.txt");
if(file.exists()){
}else{
file.createNewFile();
}
BufferedInputStream bis = new BufferedInputStream(System.in);
FileOutputStream fos = new FileOutputStream(file);
byte[] str = new byte[1024];
if(str.length != 0){
bis.read(str);
fos.write(str);
}
bis.close();
fos.close();
}
}