java吧 关注:1,243,831贴子:12,717,207
  • 4回复贴,共1

Copy 文件时复制内容失败, 请求大神指导:

只看楼主收藏回复

package TestingFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Demo01 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
copyFile("D:\\QQ\\1.txt","E:\\");
}
public static void copyFile(String src, String des) throws IOException {
File file1 = new File(src); //源文件所在地址
File fileDir = new File(des); //目标地址
String topath = des + "\\" + file1.getName();
File file2 = new File(topath);
if(!fileDir.exists()){
fileDir.mkdirs();s
}
InputStream in = new FileInputStream(src);
FileOutputStream fs = new FileOutputStream(topath);
byte[] buffer = new byte[]{}; //创建一个接收数据的数组
int length;
int byteread=0;
int bytesum = 0;
while((byteread = in.read(buffer))!=-1){
// bytesum += byteread;
//System.out.print(bytesum);
fs.write(buffer, 0, byteread);
}
in.close();
fs.close();
System.out.println("successfully" + topath);
}
}


IP属地:安徽1楼2015-11-23 09:44回复
    输出结果是只把文件复制到目标地址,但是文件内容没有一起复制过去、


    IP属地:安徽2楼2015-11-23 09:46
    回复
      des参数传入"E:\\1.txt"


      IP属地:广东来自Android客户端3楼2015-11-23 09:46
      回复
        我又尝试了一遍,还是只能把文件拷过去,内容没有显示在目标文件夹下的文件内。
        package TestingFile;
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        public class Demo2 {
        public static void main(String[] args) throws IOException {
        copyFile("D:\\QQ\\1.txt","E:\\1.txt");
        }
        public static void copyFile(String src, String des) throws IOException {
        File f1 = new File(src);
        File f2 = new File(des);
        String toPath = des + "\\" + f1.getName();
        if(!f2.exists()){
        f2.createNewFile();
        }
        InputStream in = new FileInputStream(src);
        FileOutputStream fs = new FileOutputStream(des);
        byte[] buffer = new byte[512];
        int rs = -1;
        while((rs = in.read())>0){
        fs.write(buffer, 0, rs);
        }
        in.close();
        fs.close();
        System.out.println("successfully" + toPath);
        }
        }


        IP属地:安徽4楼2015-11-23 10:42
        回复
          运行结果后的目标文件没内容:


          IP属地:安徽5楼2015-11-23 10:44
          回复