Java实现复制文本文件的两种方法
FileChannel这个类是继承于抽象类AbstractInterruptibleChannel,实现了接口ByteChannel,GatheringByteChannel,ScatteringByteChannel。
FileChannel这个是最便捷的方法实现复制文件,当然也有一种笨的方法实现复制文件,用读取文件,创建文件,写入文件的方法实现FileChannel这个方法
FileChannel 方法实现复制文本
public class MainCopy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileChannel in=null;
FileChannel out=null;
File f1=new File("channel1.txt");
File f2=new File("channel2.txt");
try {
in=new FileInputStream(f1).getChannel();
ByteBuffer byteBu=in.map(FileChannel.MapMode.READ_ONLY, 0,f1.length());
out=new FileOutputStream(f2).getChannel();
out.write(byteBu);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
用读写文件的方法实现
<pre name="code" class="java">public class MainCopy2 {
static PrintWriter pw=null;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//读取文件
InputStream in=new FileInputStream("channel1.txt");
InputStreamReader iread=new InputStreamReader(in);
BufferedReader bf=new BufferedReader(iread);
//复制文件
File f2=new File("channel2.txt");
OutputStream os=new FileOutputStream(f2);
OutputStreamWriter ow=new OutputStreamWriter(os);
pw=new PrintWriter(ow);
String len=null;
while((len=bf.readLine())!=null){
copyfile(len);
}
bf.close();
pw.close();
}
//复制两个文件的内容
static void copyfile(String content) throws FileNotFoundException{
pw.println(content);
}
}