java怎样实现文件拷贝?
解决方案 »
- swing jTable删除一条记录后,jTable中的这条记录也被删除
- 服务器集群和负载均衡
- 数组为空报错
- 发一些问题,随便不是很重要,但是挺想知道原因的。
- 跪求:java.net.SocketException: 在一个非套接字上尝试了一个操作
- 进过这个的http://community.csdn.net/Expert/topic/4457/4457136.xml?temp=.9987757大虾来jf
- <Thinking in JAVA>中文chm版下载
- 请问怎样设置JTree对象的图标
- 请教scrollpanel里是否只能在控件向下排列的时候,才能出线滚动条?如果控件向顶部排列,并且超过顶部的时候如何出现滚动条?
- 谁有JBuilder3.5的注册码???
- SWT 怎么设置表格的高度和表中的行数相对应? 就是不出现没有用的行
- 想知道那些是常见的运行时异常?请列举
public static void main(String[] args) {
if (args.length!=2) //检测程序是否有两个参数
System.err.println("Usage: java FileCopy <source> <destination>");
else {
try { copy(args[0],args[1]); }
catch(IOException e) { System.err.println(e.getMessage()); }
}
} public static void copy(String from_name,String to_name) throws IOException {
File from_file=new File(from_name); //获取file对象
File to_file=new File(to_name); if(!from_file.exists()) //确定原文件是否存在
abort("no such source file: "+from_name);
if(!from_file.isFile()) //确定是否是一个文件
abort("can't copy directory: "+from_name);
if(!from_file.canRead()) //确定文件是否可读
abort("source file is unreadable: "+from_name); if(to_file.isDirectory()) //如果目标是目录,将原文件名做为目标文件名
to_file=new File(to_file,from_file.getName()); //既将该目录的名称用做目标文件的名称 if(to_file.exists()) {
if(!to_file.canWrite()) //如果目标存在,确定是否可写
abort("destination file is unwriteable: "+to_name);
System.out.print("Overwrite existing file "+to_file.getName()+"?(Y/N):"); //如果可写,确定是否可以覆盖
System.out.flush();
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); //获取用户响应
String response=in.readLine();
if(!response.equals("Y")&&!response.equals("y")) //如果是yes,放弃复制
abort("existing file was not overwritten.");
}
else { //如果文件不存在,检测目录是否存在,是否可写
String parent=to_file.getParent(); //目标目录
if(parent==null) //如果getParent返回null,则目录是当前目录
parent=System.getProperty("user.dir");
File dir=new File(parent); //并将目录转换成文件
if(!dir.exists())
abort("destination directory doesn't exist: "+parent);
if(dir.isFile())
abort("destination is not a directory: "+parent);
if(!dir.canWrite())
abort("destination directory is unwriteable: "+parent);
}
//到此说明一切正常
FileInputStream from=null; //置源流
FileOutputStream to=null; //置目标流
try {
from=new FileInputStream(from_file); //创建输入流
to=new FileOutputStream(to_file); //创建输出流
byte[] buffer=new byte[4096]; //保存文件内容到buffer
int bytes_read; //缓冲区大小
while((bytes_read=from.read(buffer))!=-1) //读直到文件末尾
to.write(buffer,0,bytes_read); //写入buffer
}
finally { //关闭流(永远不要忘记)
if(from!=null) try { from.close(); } catch(IOException e) { ; }
if(to!=null) try { to.close(); } catch(IOException e) { ; }
}
} private static void abort(String msg) throws IOException { //异常抛出的简单程序
throw new IOException("FileCopy: "+msg);
}
}
import java.nio.channels.*;
import java.io.*;
public class ChannelDemo {
public static void main(String args[])
throws IOException {
// check command-line arguments
if (args.length != 2) {
System.err.println("missing filenames");
System.exit(1);
}
// get channels
FileInputStream fis =
new FileInputStream(args[0]);
FileOutputStream fos =
new FileOutputStream(args[1]);
FileChannel fcin = fis.getChannel();
FileChannel fcout = fos.getChannel();
// do the file copy
fcin.transferTo(0, fcin.size(), fcout);
// finish up
fcin.close();
fcout.close();
fis.close();
fos.close();
}
}
// Demonstrates the use of the File class to
// create directories and manipulate files.
import java.io.*;public class MakeDirectories {
private final static String usage =
"Usage:MakeDirectories path1 ...\n" +
"Creates each path\n" +
"Usage:MakeDirectories -d path1 ...\n" +
"Deletes each path\n" +
"Usage:MakeDirectories -r path1 path2\n" +
"Renames from path1 to path2\n";
private static void usage() {
System.err.println(usage);
System.exit(1);
}
private static void fileData(File f) {
System.out.println(
"Absolute path: " + f.getAbsolutePath() +
"\n Can read: " + f.canRead() +
"\n Can write: " + f.canWrite() +
"\n getName: " + f.getName() +
"\n getParent: " + f.getParent() +
"\n getPath: " + f.getPath() +
"\n length: " + f.length() +
"\n lastModified: " + f.lastModified());
if(f.isFile())
System.out.println("it's a file");
else if(f.isDirectory())0D
System.out.println("it's a directory");
}
public static void main(String[] args) {
if(args.length < 1) usage();
if(args[0].equals("-r")) {
if(args.length != 3) usage();
File
old = new File(args[1]),
rname = new File(args[2]);
old.renameTo(rname);
0A fileData(old);
fileData(rname);
return; // Exit main
0A }
int count = 0;
boolean del = false;
if(args[0].equals("-d")) {
count++;
del = true;
}
for( ; count < args.length; count++) {
File f = new File(args[count]);
if(f.exists()) {
System.out.println(f 2B " exists");
if(del) {
System.out.println("deleting..." + f);
f.delete();
}
}
else { // Doesn't exist0D
if(!del) {
f.mkdirs();
System.out.println("created " + f);
}
}
fileData(f);
}
}
} ///:~在fileData()中,可看到应用了各种文件调查方法来显示与文件或目录路径有关的信息。
main()应用的第一个方法是renameTo(),利用它可以重命名(或移动)一个文件至一个全新的路径(该路径由参数决定),它属于另一个File对象。这也适用于任何长度的目录。
若试验上述程序,就可发现自己能制作任意复杂程度的一个目录路径,因为mkdirs()会帮我们完成所有工作。==============================
在下所说,也许并非正确,请从建议的角度
/**
* 文件拷贝。
*
*@param from 源路径。
*@param to 目标路径。
*@exception IOException Description of the Exception0D
*/
public static void copy( String from, String to )
throws IOException
{
int BUFF_SIZE = 100000;
byte[] buffer = new byte[ BUFF_SIZE ];
InputStream in = null;
OutputStream out = null; try
{
in = new FileInputStream( from );0D
out = new FileOutputStream( to );0D while ( true )
{
synchronized ( buffer )
{
int amountRead = in.read( buffer ); if ( amountRead == -1 )
{
break;
} out.write( buffer, 0, amountRead );
0A }
}
}
finally
{
if ( in != null )
{
in.close();
} if ( out != null )
{
out.close();0D
}
}
}
================================================================
Someone