Java编程文件 *** 作,将一个文件的内容复制到另一个文件中,案例代码如下:
package example;import javaioFile;
import javaioFileInputStream;
import javaioFileNotFoundException;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javaioOutputStream;
/
将一个文件的内容复制到另一个文件中 要采边读边写的模式,这样效率才会高
@author Administrator
/
public class Copy {
public static void main(String[] args) {
// TODO Auto-generated method stub
Systemoutprintln(argslength);
/
在args参数中传进两个文件的路径,可以在run as->run configuration的arguments设置args的参数
/
if (argslength != 2) {
Systemoutprintln("输入的参数不正确!");
Systemexit(1);
}
File file1 = new File(args[0]);
File file2 = new File(args[1]);
if (!file1exists()) {
Systemoutprintln("源文件不存在!");
}
InputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
OutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file2, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
if (fileInputStream != null && fileOutputStream != null) {
int temp = 0;
try {
/
边读边写
/
while ((temp = fileInputStreamread()) != -1) {
fileOutputStreamwrite(temp);
}
Systemoutprintln("复制完成");
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
Systemoutprintln("复制失败");
} finally {
try {
fileInputStreamclose();
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
try {
fileOutputStreamclose();
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
}
}
}借助工具包commons-iojar
import javaioFile;
import javaioIOException;
import orgapachecommonsioFileUtils;
public class Admin {
public static void main(String[] args) {
File from = new File("d:/a");
File to = new File("d:/b");
try {
FileUtilscopyDirectory(from, to);
} catch (IOException e) {
eprintStackTrace();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)