2016-12-06 42 views
0

的一段代碼到目前爲止,我已經寫了情況如下:如何從android手機目錄中讀取圖像,重命名並複製回相同的目錄?

String fname = type + (i + 1) + "-" + ext; 

String fname1 = type + (i + 2) + "-" + System.currentTimeMillis() + ext; 

File file = new File(myDir, fname); 

if (file.exists()) { 

    //file.delete(); 

    continue; 

} else { 

    try { 

     InputStream in = getResources().openRawResource(x); 

     FileOutputStream outStream = new FileOutputStream(file); 

     byte[] buff = new byte[1024]; 

     byte[] buff1 = new byte[1024]; 

     int read = 0; 

     try { 

      while ((read = in.read(buff)) > 0) { 

      outStream.write(buff, 0, read); 

      //I wanted to fasten up the process so i added the code below: I have tried multiple way to do the same 


      //FileInputStream fi = new FileInputStream(myDir+File.separator+fname); 

      File File1 = new File(Environment.getExternalStorageDirectory()+File.separator + 
      "Application"+File.separator + "/Images" + "Image1-.jpg"); 

      File File2 = new File(Environment.getExternalStorageDirectory()+File.separator + "Application"+File.separator + "/Images" + fname1); 

      //String name = in1.getName(); 

      File newname = new File(fname1); 

      File1.renameTo(newname); 

      FileUtils.copyDirectory(File1, File2); 

     } 

finally { 

    in.close(); 

    outStream.close(); 

} 

但是,這是行不通的。 任何人都可以給我一些建議如何解決這個問題?

回答

0

您可以通過這個 -

file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg"); 

調用回寫()函數讀取目錄的圖像,並通過文件路徑和名稱

String shiftedPath = copyBack(file.getAbsolutePath(),newName); 

//函數使用了複製和重命名

public String copyBack(String srcPath,String newName) { 
//you can defined path of same directory as per your requirement, and just pass new 
      file = new File(Environment.getExternalStorageDirectory() + File.separator + "newName"); 
      file.mkdirs(); 
      try { 
    //   File sd = Environment.getExternalStorageDirectory(); 
    //   File data = Environment.getDataDirectory(); 

       String sourceImagePath = srcPath; 
       String destinationImagePath = file.getAbsolutePath(); 
       File source = new File(sourceImagePath); 
       destination = new File(file, ".image"); 
       if (source.exists()) { 
        FileChannel src = new FileInputStream(source).getChannel(); 
        FileChannel dst = new FileOutputStream(destination).getChannel(); 
        dst.transferFrom(src, 0, src.size()); 
        src.close(); 
        dst.close(); 

       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      return destination.getAbsolutePath(); 
     } 
+0

親愛的Nishchal,謝謝你的回覆......但這個解決方案不起作用。我在這個應用程序中試圖做的是:我通過在設備中創建一個新目錄,將圖像文件從應用程序資源複製到設備。但需要時間。因此,爲了在將應用程序中的圖像複製到設備時提高性能,我還從設備位置獲取第一個複製圖像,並將其重命名並粘貼回同一目錄。 –

相關問題