直接用javaio拷贝文件不就完了。下面的这个是用NIO实现的,可以拷贝文件或目录 public void copyFileNIO(File from, File to) {
try {
if (from.isDirectory()) {
to.mkdirs();
} else {
if (!to.getParentFile().exists()) {
to.getParentFile().mkdirs();
}
if (to.exists()) {
to.delete();
}
if (from.exists()) {
FileChannel channelSrc = new FileInputStream(from).getChannel();
FileChannel channelDest = new FileOutputStream(to).getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
while (-1 != channelSrc.read(buf)) {
buf.flip();
channelDest.write(buf);
buf.clear();
}
channelDest.close();
channelSrc.close();
}
}
to.setLastModified(from.lastModified()); } catch (Exception e) {
e.printStackTrace();
} }
try {
if (from.isDirectory()) {
to.mkdirs();
} else {
if (!to.getParentFile().exists()) {
to.getParentFile().mkdirs();
}
if (to.exists()) {
to.delete();
}
if (from.exists()) {
FileChannel channelSrc = new FileInputStream(from).getChannel();
FileChannel channelDest = new FileOutputStream(to).getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
while (-1 != channelSrc.read(buf)) {
buf.flip();
channelDest.write(buf);
buf.clear();
}
channelDest.close();
channelSrc.close();
}
}
to.setLastModified(from.lastModified()); } catch (Exception e) {
e.printStackTrace();
} }
我在Servlet里用了你写的copyFileNIO,编译是通过了.
然后用tomecat启动,可是Weblogic报错说:
java.lang.NoSuchMethodError
显示的是FileChannel channelSrc = new FileInputStream(from).getChannel();
这一行有问题.请问是怎么回事?
——————————————————————————————————————NIO是jdk1.4加入的,出这个错误的原因可能是你运行的jre是1.4以前的那就不要用NIO了 private void copyFile(File from, File to) {
try {
if (from.isDirectory()) {
to.mkdirs();
} else {
if (!to.getParentFile().exists()) {
to.getParentFile().mkdirs();
}
if (to.exists()) {
to.delete();
}
if (from.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
to.setLastModified(from.lastModified());
} catch (Exception e) {
e.printStackTrace();
}
}