[英]Writing a File using FileOutput Stream
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()方法無法關閉打開的文件? ima初學者,熱衷於學習編程。 THK在先進!
您這里有一個無限循環(調試器會確認這一點)
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.