1

如何将文件从资产复制到 Android 的内部存储?

我有将文件从资产复制到外部存储的代码,但我需要将文件复制到内部存储。

我在做什么?我为华为/EMUI设备设计了图标和主题。我需要应用图标和主题将它们传输到带有华为/主题文件夹的华为/EMUI 设备和按钮。

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);
        }
    }
}
4

1 回答 1

1

要将压缩文件夹从资产复制到内部存储,您可以使用它

/**
 * unzips the silder games bundle zip file into Internal Storage : Mayank Bhatnagar (mbhatnagar@ivycomptech.com)
 *
 * @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 (mbhatnagar@ivycomptech.com)
 *
 * @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 (mbhatnagar@ivycomptech.com)
 *
 * @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);
    }
}

像这样从内部存储中读取复制的数据

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();
        }
    }

希望这可以帮助。

于 2018-07-07T14:18:40.330 回答