Java复制文件
private boolean copyFile ( String oldFile, String newFile) {
InputStream is = null;
OutputStream os = null;
StringBuilder stringBuilder = new StringBuilder ( ) ;
try {
is = new FileInputStream ( oldFile) ;
os = new FileOutputStream ( newFile) ;
byte [ ] flush = new byte [ 1024 ] ;
int len;
while ( ( len = is. read ( flush) ) != - 1 ) {
os. write ( flush, 0 , len) ;
}
os. flush ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
try {
if ( null != os) {
os. close ( ) ;
}
if ( null != is) {
is. close ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
if ( new File ( newFile) . exists ( ) ) {
return true ;
}
return false ;
}
复制文件夹
import java. io. *;
import java. time. Duration;
import java. time. Instant;
public class CopyDir {
public static void main ( String[ ] args) {
Instant start = Instant. now ( ) ;
boolean isOk = dirOrFile ( "要复制的目录路径" , "目标路径" ) ;
if ( isOk) {
System. out. println ( "目录复制完成!" ) ;
} else {
System. out. println ( "目录复制失败!" ) ;
}
Instant end = Instant. now ( ) ;
System. out. println ( "耗时:" + Duration. between ( start, end) . toMillis ( ) + "毫秒!" ) ;
}
private static boolean copyDir ( String oldDir, String newDir) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream ( oldDir) ;
os = new FileOutputStream ( newDir) ;
byte [ ] flush = new byte [ 1024 ] ;
int len;
while ( ( len = is. read ( flush) ) != - 1 ) {
os. write ( flush, 0 , len) ;
}
os. flush ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} finally {
try {
if ( null != os) {
os. close ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
if ( null != is) {
is. close ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
return false ;
}
private static boolean dirOrFile ( String oldDir, String newDir) {
File old = new File ( oldDir) ;
File copy = new File ( newDir) ;
if ( old. isDirectory ( ) ) {
copy. mkdir ( ) ;
File[ ] files = old. listFiles ( ) ;
for ( int i = 0 ; i < files. length; i++ ) {
dirOrFile ( files[ i] . getAbsolutePath ( ) , newDir + "/" + files[ i] . getName ( ) ) ;
}
}
if ( old. isFile ( ) ) {
copyDir ( oldDir, newDir) ;
}
if ( old. length ( ) == copy. length ( ) ) {
return true ;
}
return false ;
}
}