Java每日一题04

昨天本来想写一段很简单的小程序,关于文件复制,但是遇到了问题,所以把问题提出来,希望大家能够帮我解决,万分感谢!
[color=blue]如何将一个文件从一个目录复制到另一个目录?[/color]
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(System.getProperty("user.dir")
+ "\\DejaVuSansMono-Bold.ttf");
out = new FileOutputStream(
"C:\\WINDOWS\\Fonts\\DejaVuSansMono-Bold.ttf");

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} 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();
}
}
}

}


或者
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileCopy2 {

public static void main(String[] args) {
try {
FileChannel srcChannel = new FileInputStream(System
.getProperty("user.dir")
+ "\\DejaVuSansMono-Bold.ttf").getChannel();

FileChannel dstChannel = new FileOutputStream(
"C:\\WINDOWS\\Fonts\\DejaVuSansMono-Bold.ttf").getChannel();

dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

srcChannel.close();
dstChannel.close();
} catch (IOException e) {
}
}

}

以上是两个很常见的写法,分别用了IO和NIO,我愿意为复制就是这么简单,但却遇到了一个解决不了的问题,详情请见
[url]http://jythoner.iteye.com/admin/blogs/323566[/url]

今天早晨又想另辟蹊径,写了第三种方法(这种方法我以为可以成功,但是却在执行是出现了Exception):
import java.io.IOException;

public class FileCopy3 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {
String[] command = new String[] {
"copy",
System.getProperty("user.dir")
+ "\\DejaVuSansMono-Bold.ttf", "E:\\1.txt",
"C:\\Windows\\Fonts\\" };
Process child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


异常信息是:
java.io.IOException: Cannot run program "copy": CreateProcess error=2, ?????????
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at FileCopy3.main(FileCopy3.java:17)
Caused by: java.io.IOException: CreateProcess error=2, ?????????
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 4 more
希望有经验的朋友帮忙看看,再次感谢!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值