当前位置: 代码迷 >> J2SE >> RandomAccessFile 传输文件时出错,该怎么解决
  详细解决方案

RandomAccessFile 传输文件时出错,该怎么解决

热度:633   发布时间:2016-04-23 20:05:22.0
RandomAccessFile 传输文件时出错
我运行以下代码:
String filePath = "D:\\aa.rar";
File files = new File(filePath);
int start = 0;
int byteLen = (int) files.length();
byte[] resultBs = new byte[byteLen];
try {
RandomAccessFile randFile = new RandomAccessFile(filePath, "rw");
randFile.seek(0);
randFile.write(resultBs, start, byteLen);
File f = new File("D:"+File.separator+"testfile.rar");
OutputStream out = new FileOutputStream(f,true);
out.write(resultBs);
randFile.close();

在d盘下可以生成testfile.rar文件,但我打开这个文件的时候报文件损坏。有没有人知道我上面的代码哪个地方有问题?
------解决思路----------------------
randFile.write(resultBs, start, byteLen);
应该是read方法吧??
------解决思路----------------------
写的有点混了,不知道楼主是想用RandomAccessFile还是OutputStream把文件写入磁盘
改了下,可以参考下
public static void main(String args[]) throws IOException {
String filePath = "D:\\aa.rar";
String dest="D:" + File.separator + "testfile.jar";
int flag=copyFileToDest(filePath,dest);
System.out.println("文件复制"+(flag==1?"成功":"失败"));

}

public static int copyFileToDest(String src,String dest){
int flag=1;
File files = new File(src);
int start = 0;
int byteLen = (int) files.length();
byte[] resultBs = new byte[byteLen];
RandomAccessFile randFile = null;
try {
InputStream ins = new FileInputStream(files);
ins.read(resultBs, start, byteLen);
randFile = new RandomAccessFile(dest, "rw");
randFile.write(resultBs, start, byteLen);
ins.close();
randFile.close();
} catch (Exception e) {
flag=0;
e.printStackTrace();

}
return flag;

}