Javaを使用してある場所から別の場所に画像ファイルをコピーしようとしています。ここで、ソースの場所にある画像ファイルのサイズに関係なく、特定のサイズの画像ファイルを保存したいと思います。
私は次のコードを使用しています、それはソースファイルと同じサイズで宛先の場所に画像を生成しています:
public class filecopy {
public static void copyFile(File sourceFile, File destFile)
throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size
- count)) < size)
;
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
public static void main(String args[]) {
try {
File sourceFile = new File("D:/new folder/abc.jpg");
File destFile = new File("d:/new folder1/abc.jpg");
copyFile(sourceFile,destFile);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}