比如说读取d:\1.txt的文件内容,其中里面包括若干个回车,把读取到的内容复制到d:\2.txt中,让2.txt和1.txt内容和格式都完全一样。我用下面这段代码复制文件后,在2.txt中每一个回车都被一个小黑块代替,郁闷
主要代码:
public static void main(String[] args) throws Exception {
FileReader fis=new FileReader("d:\\1.txt");
BufferedReader br=new BufferedReader(fis);
String str="";
String str1=null;
while((str1=br.readLine())!=null)
{
str1+="\r";
str+=str1;
}
FileWriter fw=new FileWriter("d:\\2.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write(str);
bw.close();
fw.close();
}请问怎么写代码才能满足我上面说的那些条件呢?即复制后两个文件的内容和格式完全一样。谢谢

解决方案 »

  1.   

    public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("d:\\1.txt");
    BufferedInputStream br = new BufferedInputStream(fis); FileOutputStream fw = new FileOutputStream("d:\\2.txt");
    BufferedOutputStream bw = new BufferedOutputStream(fw);
    int a;
    while ((a = br.read()) != -1) {
    bw.write(a);
    }
    bw.close();
    fw.close();
    }
      

  2.   

    public static boolean copyFile(String srcfile, String destfile) {
            try {
                File file = new File(destfile);
                file.createNewFile();            File iFile = new File(srcfile);
                File oFile = new File(destfile);            FileReader in  = new FileReader(iFile);
                FileWriter out = new FileWriter(oFile);            int c;
                while ((c = in.read()) != -1) {
                    out.write(c);
                }            in.close();
                out.close();
                return true;
            } catch (IOException e) {
                return false;
            }
        }
      

  3.   

    下面的代码能够复制一个文件目录下的所有文件和文件夹
    import java.io.*;public class Filecopy { /**
     * @param args
     */
      public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
        if (args.length == 0)
    args = new String[] { "g:\\2", "g:\\1" };
        File frompath = new File(args[0]);
        File topath = new File(args[1]);
        String[] fromlist = frompath.list();
        for (int i = 0; i < fromlist.length; i++) {
    File fromfile = new File(frompath.getPath(), fromlist[i]);
    File tofile = new File(topath.getPath(), fromlist[i]);
    if (fromfile.isDirectory()) {
        tofile.mkdirs();
        System.out.println( fromfile.getCanonicalPath());
        main(new String[] { fromfile.getPath(), tofile.getPath() });
    }
    else {
        int ch;
        byte[] b = new byte[256];
        RandomAccessFile fin = new RandomAccessFile(fromfile, "r");
        RandomAccessFile fout = new RandomAccessFile(tofile, "rw");
        ch = fin.read(b);
        while (ch != -1) {
    fout.write(b);
    ch = fin.read(b);
        }
        fin.close();
        fout.close();
    }
         }
      }
    }
      

  4.   

    按行读肯定不行,linux和windows定义的换行符可能不同,你可以首先获取文件大小,然后整个读,或者一个byte一个byte的读。