Reputation: 7
How can I copy a file from assets to internal storage in Android?
I have the codes for copying file from assets to external storage but I need to copy file to internal storage.
What I'm doing? I designed icon and theme for Huawei / EMUI devices. I need to apply icons and themes to transfer them to Huawei / EMUI devices with Huawei / Themes folder with button.
package com.grafiman.selero.selero;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_STORAGE = 1;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE);
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_STORAGE);
}
} else{
}
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
copyFileFromAssets("selero.hwt");
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_REQUEST_STORAGE: {
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED){
}else{
Toast.makeText(this,"You have not permission!!",Toast.LENGTH_SHORT).show();
}
}
}
}
}
private void copyFileFromAssets(String fileName){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Huawei/Themes";
File file = new File(dirPath);
if(!file.exists()){
file.mkdirs();
}
AssetManager assetManager = getAssets();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = assetManager.open(fileName);
File outputFile = new File(dirPath, fileName);
outputStream = new FileOutputStream(outputFile);
copyFile(inputStream,outputStream);
Toast.makeText(this,"Saved Successfully!",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this,"Error!",Toast.LENGTH_SHORT).show();
}
}
private void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer,0,read);
}
}
}
Upvotes: 1
Views: 4644
Reputation: 2191
To copy a zipped folder from assets to Internal Storage you can use this
/**
* unzips the silder games bundle zip file into Internal Storage : Mayank Bhatnagar ([email protected])
*
* @param context: {@link Context} instance
* @param zipFileName: zip file name kept in assets
* @param storageLocation: ineternal storage locaton for copying slider games
*/
@WorkerThread
public static boolean unzipSliderGames(Context context, String zipFileName, String storageLocation, boolean fromAssets) {
try {
InputStream fileInputStream = null;
if (fromAssets) {
AssetManager assetManager = context.getAssets();
fileInputStream = assetManager.open(zipFileName);
}else
fileInputStream = new FileInputStream(context.getFilesDir().getAbsolutePath() + File.separator + zipFileName);
ZipInputStream in = new ZipInputStream(fileInputStream);
ZipEntry zipEntry = null;
FileOutputStream out = null;
while ((zipEntry = in.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + zipEntry.getName());
if (zipEntry.isDirectory()) {
createDirectory(storageLocation + File.separator, zipEntry.getName());
} else {
out = new FileOutputStream(storageLocation + File.separator + zipEntry.getName());
copyFile(in, out);
}
}
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + zipEntry.getName(), e);
}
}
if (out != null) {
try {
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + zipEntry.getName(), e);
}
}
Log.d("Unzip", "Unzipping complete. path : " + storageLocation);
return true;
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
Log.d("Unzip", "Unzipping failed");
}
return false;
}
/**
* creates a directory if not exists : Mayank Bhatnagar ([email protected])
*
* @param directoryPath: path at which directory is to be created
* @param name: directory name
*/
private static void createDirectory(String directoryPath, String name) {
File file = new File(directoryPath + name);
if (!file.isDirectory()) {
file.mkdirs();
}
}
/**
* copies the files contents : Mayank Bhatnagar ([email protected])
*
* @param in: {@link InputStream} stream of input data
* @param out: {@link OutputStream} stream of putput data
* @throws IOException
*/
private static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Read copied data from Internal storage like this
public void readFile(Context context){
try {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
String filePath = context.getFilesDir();
File folder = new File(filePath );
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.getName().endsWith(".html")) {
String game = file.getName().substring(0, file.getName().indexOf("."));
map.put(game, file.getPath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hope this helps.
Upvotes: 2