package e2;
import java.io.*;
public class Copy {
Copy(){};//构造方法
void CopyFile(File sFile, File dFile){
try {
InputStream in = new FileInputStream(sFile);//文件字节输入流
OutputStream out = new FileOutputStream(dFile,true);//文件字节输出流
long n = sFile.length(); //要复制文件的大小,length()方法返回文件字节数
int b = (int)n; //把n强制转换为整型
byte a[] = new byte[b];
in.read(a,0,b); //从源sFile读出内容到数组a中,
out.write(a,0,b);//从a中读出内容到dFile
in.close();
out.close();
}
catch(IOException e) {
System.out.println(e.toString());
}
}
}
package e2;
import java.io.*;
public class Test {
public static void main(String args[]) {
File sFile = new File("source.txt");//俩文件
File dFile = new File("backup.txt");
try {
if(!sFile.exists()) {
sFile.createNewFile();
}
if(!dFile.exists()) {
dFile.createNewFile();
}
}
catch(IOException e) {
System.out.println(e.toString());
}
Copy copy = new Copy();
copy.CopyFile(sFile,dFile );
}
}
本文提供了一个简单的Java程序示例,用于演示如何将一个文件的内容复制到另一个文件中。通过使用FileInputStream和FileOutputStream,程序实现了文件的读取与写入操作,并确保了文件能够被正确复制。
654

被折叠的 条评论
为什么被折叠?



