功能描述:
文件夹a中存放已经处理好的图片,文件夹b中存的是之前的图片(且可能有多级文件夹)
现在需要将a文件夹中处理好的图片替换到b文件中,以图片的名字和后缀名做替换条件。
import java. io. * ;
import java. util. HashMap ;
public class GetResolutionRatio {
public static final String endWith = ".png" ;
public static int num = 0 ;
public static final HashMap < String , File > map = new HashMap < > ( ) ;
public static void main ( String [ ] args) throws IOException {
String sourcePath = "C:\\Users\\lenovo\\Desktop\\source" ;
File sourceFile = new File ( sourcePath) ;
sourceFinDiGui ( sourceFile) ;
String path = "C:\\Users\\lenovo\\Desktop\\images" ;
File file = new File ( path) ;
finDiGui ( file) ;
System . out. println ( "处理数量" + num) ;
}
public static void finDiGui ( File file) throws IOException {
if ( file. isDirectory ( ) ) {
File [ ] listFiles = file. listFiles ( ) ;
for ( File f : listFiles) {
finDiGui ( f) ;
}
}
if ( file. getName ( ) . endsWith ( ".png" ) ) {
System . out. println ( "文件夹" + file) ;
File tu = map. get ( file. getName ( ) ) ;
if ( tu!= null ) {
copy ( tu, file) ;
num++ ;
}
}
}
public static void sourceFinDiGui ( File file) throws IOException {
if ( file. isDirectory ( ) ) {
File [ ] listFiles = file. listFiles ( ) ;
for ( File f : listFiles) {
sourceFinDiGui ( f) ;
}
}
if ( file. getName ( ) . endsWith ( ".png" ) ) {
map. put ( file. getName ( ) , file) ;
}
}
public static void copy ( File srcPath, File destPath) {
InputStream is= null ;
OutputStream os= null ;
try {
is= new FileInputStream ( srcPath) ;
os= new FileOutputStream ( destPath) ;
byte [ ] flush= new byte [ 1024 ] ;
int len= - 1 ;
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) {
}
try {
if ( null != is) {
is. close ( ) ;
}
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
}