java 把a文件复制到b
来源:百度知道 编辑:UC知道 时间:2024/05/10 12:22:28
import java.io.*;
class MyCopy{
public static String tellfile(){
String str = null;
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str = br.readLine();
}catch(IOException e){
e.printStackTrace();
System.out.println("输入错误");
}
return str;
}
String out = null;
public static String mycopy(String in,String out ){
try{
FileReader fr = new FileReader(in);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(out);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(br.read()!=-1){
pw.print(out);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
return out;
复制文件,如图片,音乐文件,建议用字节流.
你没有关闭流.
在mycopy方法的while块后添加下面两行.
br.close();
bw.close();
我写的小例子.
package test;
import java.io.*;
public class FileTest{
public static void main(String[] args){
File from=new File("src\\test\\FileTest.java");
File to=new File("src\\xxxx\\FileTest2.java");
copyFile(from,to);
}
public static void copyFile(File from,File to){
BufferedInputStream in=null;
BufferedOutputStream out=null;
try{
if(!from.exists()){
return;
}
if(!to.exists()){
File toDir=new File(to.getParent());
toDir.mkdirs();
to.createNewFile();
}
in=new BufferedInputStream(new FileInputStream(from));
out=new BufferedOutputStream(new FileOutputStream(to));
int b=0;
while((b=in.read())!=-1){
out.write(b);