다음 예제는 스트림을 사용하여 파일을 복사하는 방법을 보여줍니다. 상기의 코드 용 스트림이있는 파일 복사
private void copyWithStreams(File aSourceFile, File aTargetFile, boolean aAppend) {
log("Copying files with streams.");
ensureTargetDirectoryExists(aTargetFile.getParentFile());
InputStream inStream = null;
OutputStream outStream = null;
try{
try {
byte[] bucket = new byte[32*1024];
inStream = new BufferedInputStream(new FileInputStream(aSourceFile));
outStream = new BufferedOutputStream(new FileOutputStream(aTargetFile, aAppend));
int bytesRead = 0;
while(bytesRead != -1){
bytesRead = inStream.read(bucket); //-1, 0, or more
if(bytesRead > 0){
outStream.write(bucket, 0, bytesRead);
}
}
}
finally {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
}
}
catch (FileNotFoundException ex){
log("File not found: " + ex);
}
catch (IOException ex){
log(ex);
}
}
private void ensureTargetDirectoryExists(File aTargetDir){
if(!aTargetDir.exists()){
aTargetDir.mkdirs();
}
}
private static void log(Object aThing){
System.out.println(String.valueOf(aThing));
}
는 I 네 포인트에 대해 혼란 느낌 :
1) 버킷 바이트 [] = 버킷 새로운 바이트 [32 * 1024]로 분배한다; 32 * 1024와 같은 크기를 선택하기위한 기준이 있습니까?
2) 왜 여기에 "붙잡아 야"합니까? 작문 프로그램에 캐치를 포함시키는 규칙이 있습니까?
3) "try"사용법에 대해서는 아직 명확하지 않습니다. 저자가이 프로그램에서 중첩 된 시도를 사용하는 것 같습니다.
왜 File.Copy를 사용하지 않는가 http://msdn.microsoft.com/en-us/library/system.io.file.copy%28v=VS.110%29.aspx 또는 파일 크기가 클 경우 이 http://stackoverflow.com/questions/92114/how-can-i-copy-a-large-file-on-windows-without-copyfile-or-copyfileex – rabs
@rabs - 이것은 C# 또는 아무것도 관련이 없습니다 마이크로 소프트에게. –
그건 겨우 세입니다. –