使用FileOutput Stream编写文件

时间:2016-03-13 17:11:30

标签: java inputstream outputstream

import java.io.*;
class CopyFile 
{
    public static void main(String args[])
            throws IOException
    {
        int i;
        FileInputStream fin=null;
        FileOutputStream fout=null;

        if(args.length!=2)
        {
            System.out.println("Mention the name of Source and Destination File");
            return;
        }
        try{
            fin=new FileInputStream(args[0]);
            fout=new FileOutputStream(args[1]);

            do{
                i=fin.read();
                if(i!=-1) fout.write(i);

            }while(i!=1);

        } catch (IOException exc)
        {System.out.println("I/O Error Exception exc"+exc);
        }
        finally {
            try{
                if(fin !=null) fin.close();

            }catch (IOException exc){
                System.out.println("Error Closing the File");}

            try {
                if(fout !=null) fout.close();

            }catch (IOException exc)
            {System.out.println("Error Closing the File");
            }

        }
    }
}

以上编码将数据从源文件复制到目标文件问题::为什么Close()方法无法关闭已打开的文件。? 我是初学者,热衷于学习编程。 THK IN ADV !!

1 个答案:

答案 0 :(得分:0)

这里有一个无限循环(调试器会确认这一点)

        do{
            i=fin.read();
            if(i!=-1) fout.write(i);

        }while(i!=1); // you are checking for 1 not -1.

我建议你改成

for (int b; (b = fin.read()) != -1;)
     fout.write(b);

或者您可以使用缓冲区

try (FileInputStream fin=new FileInputStream(args[0]);
     FileOutputStream fout=new FileOutputStream(args[1])) {
    byte[] bytes = new byte[8192];
    for (int len; (len = fin.read(bytes)) > 0; )
        fout.write(bytes, 0, len);
} // try-with-resource will close the files.