Java implements instances of file copying and format changes

  • 2020-04-01 01:28:21
  • OfStack


package com.chen.lucene.image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Change2Image
{
 
 public void change2Image(String path, String savePath) throws Exception
 {
  File file = new File(path);
  if (!file.exists())
  {
   System.out.println(" The file does not exist! ");
   return ;
  }
  //The copied path is created if it does not exist
  File saveFile = new File(savePath);
  if (!saveFile.exists())
  {
   saveFile.mkdirs();
  }
  //New file full path
  String savePathNew = "";
  for (File fbean : file.listFiles())
  {
   if (fbean.isFile())
   {
    System.out.println(fbean.getName() + "t" + fbean.getAbsolutePath());
//    savePathNew = savePath + File.separator + fbean.getName()+ ".jpg";
    //Convert the.tbi format in the file name to.jpg & NBSP;
    savePathNew = savePath + File.separator + (fbean.getName().replaceAll(".tbi", ".jpg"));
    //Begin to copy
             copy(fbean ,new File(savePathNew));      
   }
  }
 }

 
 private static void copy(File fromFile, File toFile) throws Exception{  
  if (!fromFile.exists())
  {
   System.out.println(" Source file empty! ");
  }
  if (!toFile.exists())
  {
   System.out.println(" Create a new file. ");
   toFile.createNewFile();
  }
  FileInputStream  fis = new FileInputStream(fromFile);
        System.out.println("fromFile :" + fromFile.getAbsolutePath());
        FileOutputStream fos = new FileOutputStream(toFile);
        System.out.println("toFile :" + toFile.getAbsolutePath());

        int len = 0;  
        byte[] buf = new byte[1024];  
        while((len = fis.read(buf)) != -1){  
         fos.write(buf,0,len);  
        }

        fis.close();  
        fos.close();  
    }  

 
 public static void main(String[] args)
 {
//  String path = "E:/temp";
  String path = "E:/temp/3 Monthly packet (1)/3 Monthly packet ";
  String savePath = "E:/temp/img";
  Change2Image change2Image = new Change2Image();
  try
  {
   change2Image.change2Image(path, savePath);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  System.out.println(" complete ");
 }
}


Related articles: