2017-01-18 10 views
-1

ボタンを作成して、特定のファイルを外部ドライブに移動する必要があります。外部記憶装置に書き込むことができるようにマニフェストを設定しましたが、外部記憶装置に書き込むための特定のファイルを書き込むコードを見つけることができません。Androidのファイルを外部デバイスに移動

+0

外部記憶装置上のルート位置を指し示す 'File'オブジェクトを取得するために、' Environment'の 'Context'または' getExternalStoragePublicDirectory() 'の' getExternalFilesDir() 'または関連メソッドを使用してください。そこから、それは標準的なJavaファイルI/O(特定の場所へのそのルートに基づいて 'File'オブジェクトを作成し、' FileInputStream'と 'FileOutputStream'を開き、バイトをコピーするなど)です。 – CommonsWare

答えて

0

次の権限を持っていることを確認してください場合は、書き込み/あなたのAndroidManifest.xmlに外部メモリを読み込む:このように呼ばれる

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

copyExt("/storage/emulated/0/obb/Orange.txt",""); 

//turn String path names into File descriptors 
public void copyExt (String pathInternal, String pathExternal) { 
    File fInternal = new File (pathInternal);//pathInternal must exist 
// File fExternal = new File (pathExternal);//pathExternal must exist 
    String filename=path.substring(pathInternal.lastIndexOf("/")+1); 
    File fExternal = new File(Environment.getExternalStorage().getAbsolutePath()+"/filename"); 

    copyFile(fInternal,fExternal); 
} 

//make it static so we can re-use it, in a Utils class 
    public static void copyFile(File src, File dst) throws IOException 
    { 
     try 
     { 
      FileChannel inChannel = new FileInputStream(src).getChannel(); 
      FileChannel outChannel = new FileOutputStream(dst).getChannel(); 
      inChannel.transferTo(0, inChannel.size(), outChannel); 
     } 
     finally 
     { 
      if (inChannel != null) 
       inChannel.close(); 
      if (outChannel != null) 
       outChannel.close(); 
     } 
    } 

ALTERNATIVE

public static boolean copyFile(String from, String to) { 
try { 
    int bytesum = 0; 
    int byteread = 0; 
    File oldfile = new File(from); 
    if (oldfile.exists()) { 
     InputStream inStream = new FileInputStream(from); 
     FileOutputStream fs = new FileOutputStream(to); 
     byte[] buffer = new byte[1444]; 
     while ((byteread = inStream.read(buffer)) != -1) { 
      bytesum += byteread; 
      fs.write(buffer, 0, byteread); 
     } 
     inStream.close(); 
     fs.close(); 
    } 
    return true; 
} catch (Exception e) { 
    return false; 
} 
} 
+0

ファイル名がOrange.txtの場合、... copyExt( "/storage/emulated/0/obb/" Orange.txt "optional/external-USB/obb"); – Hyphnx

+0

ファイルが "/storage/emulated/0/obb/Orange.txt"にある場合(2番目の引数は空文字列を渡します)、次にcopyExt( "/ storage/emulated/0/obb/Orange" TXT" 、 ""); –

関連する問題