How copy Assets folder to internal storage? - java

I have copy many posible solutions from here and any unsuccess from me. I'm try to copy asset folder to storage data but always get error in logs after try to copy assets data
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
Toast.makeText(this, ""+filename, Toast.LENGTH_LONG).show();
try {
in = assetManager.open(filename);
//File outFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationInfo().packageName+"/", filename);
File outFile = new File(Environment.getExternalStorageDirectory()+"/osmdroid/", filename);
out = new FileOutputStream(outFile);
//out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private 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);
}
}
Pleasy, Any know about this error??
06-23 18:06:06.316 10803-10803/com.restaurantesencuba.myapplication E/tag: Failed to copy asset file: images
java.io.FileNotFoundException: images

I got the exact same error, actually while debugging I found "images", "sounds" and "webkit", so seems to be you should just skip the non existing ones, because there is no other way to check if they exist:
AssetManager assetManager = context.getAssets();
String[] files;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
return;
}
for(String filePath : files) {
try {
InputStream in = assetManager.open(filePath);
//do your work...
} catch (IOException ignored) { }
}

Related

Copy file from path to Path in Android 11

I hope you are fine.
After I have done all steps, of getting permission storage in Android 11, now I can create, copy files from assets to any folder, or delete files.
I just got a problem when try to copy file from path to path, the problem is I find the output file empty.
Only in this I need help, and I hope you help me and tell me what mistake I have in my code, and thanks in advance.
To copy I'm using:
Uri muri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3Aagora%2file.txt");
Uri uri2 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAlarms");
DocumentFile mfile = DocumentFile.fromTreeUri(MainActivity.this, muri);
DocumentFile mfile1 = DocumentFile.fromTreeUri(MainActivity.this, uri2);
mfile1 = mfile1.createFile("file/txt", "file.txt");
uri2 = mfile1.getUri();
if (copyFileFromUri2(MainActivity.this, muri, uri2)) {
showMessage("file copied successfully");
} else {
showMessage("failed to copy the file !");
}
The method:
public boolean copyFileFromUri2(Context context, Uri fileUri, Uri targetUri)
{
InputStream fis = null;
OutputStream fos = null;
try {
ContentResolver content = context.getContentResolver();
fis = content.openInputStream(fileUri);
fos = content.openOutputStream(targetUri);
byte[] buff = new byte[1024];
int length = 0;
while ((length = fis.read(buff)) > 0) {
fos.write(buff, 0, length);
}
} catch (IOException e) {
return false;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
return false;
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
return false;
}
}
}
return true;
}
You can try to initialize the OutputStream os as follows:
fos = new BufferedOutputStream( content.openOutputStream(targetUri))

File Handling used for saving files in a recursive manner

I have my code generating two files with rewritable data. I need a code that continues generating the files with recursive file names and should keep all the previous files as well .
In the below code, every time i have to update my file, I have to hard code it and copy it into a new file.
I want a recursive function that saves the file, named numerically in an order(Ascending), while keeping the data in my previous file as well, everytime i run the code.
public static void main(String[] args) throws IOException
{
createFileUsingFileClass();
copyFileVersion();
fileChecker();
String data_2 = "This is the new data written in your file";
writeUsingFileWriter(data_2);
copyFileInCode(data_2);
}
private static void createFileUsingFileClass() throws IOException
{
File file = new File("C:\\Users\\esunrsa\\Documents\\file.txt");
//Create the file
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
//Write Content
FileWriter writer = new FileWriter(file);
String data_1 = " Initial data";
writer.write(data_1);
writer.close();
}
private static void copyFileVersion() {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile =new File("C:\\Users\\esunrsa\\Documents\\file.txt");
File outfile =new File("C:\\Users\\esunrsa\\Documents\\file_01.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File created successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
private static void fileChecker() {
File f = new File("C:\\Users\\esunrsa\\Documents\\sunrita.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File doesnt exist");
System.exit(0);
//System.out.println("File not found!");
}
}
private static void writeUsingFileWriter(String data_2) {
File file = new File("C:\\Users\\esunrsa\\Documents\\file.txt");
FileWriter fr = null;
try {
fr = new FileWriter(file);
fr.write(data_2);
} catch (IOException e) {
e.printStackTrace();
}finally{
//close resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFileInCode(String filename) {
FileInputStream ins = null;
FileOutputStream outs = null;
try {
File infile =new File("C:\\Users\\esunrsa\\Documents\\file.txt");
File outfile =new File("C:\\Users\\esunrsa\\Documents\\file_02.txt");
ins = new FileInputStream(infile);
outs = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = ins.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
ins.close();
outs.close();
System.out.println("File created successfully!!");
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}

How can I run executable in assets?

How can I add a executable into assets and run it in Android and show the output?
I've a executable that will work. I assume there will need to be some chmod in the code.
Thank you.
here is my answer
put copyAssets() to your mainactivity.
someone's code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private 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);
}
}
also here is code to run command
public String runcmd(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer out = new StringBuffer();
while ((read = in.read(buffer)) > 0) {
out.append(buffer, 0, read);
}
in.close();
p.waitFor();
return out.substring(0);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
you may need to change it to
String prog= "programname";
String[] env= { "parameter 1","p2"};
File dir= new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(prog,env,dir);
to ensure proper parameter handling
also add this to your main code
to check proper copying of files
String s;
File file4 = new File(getFilesDir().getAbsolutePath()+"/executable");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();
//output s however you want it
should write: filename, true, true, correct filelength.
Place your executable in raw folder, then run it by using ProcessBuilder or Runtime.exec like they do here http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App

android copy database from assets folder

I having trouble coping a database from the assets folder to the databases folder. When the user start the application I check if the database doesnt exists and if true I copy the database.
Where is my code:
private void CopyDatabaseIfNotExists() {
dbName = "quizdb.db";
File f = getDatabasePath(dbName);
if (f.exists())
return;
System.out.println("db missing");
try {
InputStream mInputStream = getAssets().open(dbName);
OutputStream mOutputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = mInputStream.read(buffer)) > 0) {
mOutputStream.write(buffer, 0, length);
}
mOutputStream.flush();
mOutputStream.close();
mInputStream.close();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
And I got this error:
06-15 12:29:04.882 25037-25037/com.ex.example W/System.errīš• java.io.FileNotFoundException: /data/data/com.ex.example/databases/quizdb.db: open failed: ENOENT (No such file or directory)
I already tried search for the soluction but cant find. Somebody can help me? Thanks and sorry my english.
FileOutputStream throws this exception when the file does not exist and cannot be created. I had this probelm before and managed to solve it by first calling openOrCreateDatabase method of the Context object (or SQLiteDatabase class) before OutputStream mOutputStream = new FileOutputStream(f);
Try this...its work for me..!! and you sure you have put database file in assets folder..!!
private void copyDataBase() throws IOException {
InputStream is = myContext.getAssets().open(DB_NAME);
// Log.v("Tag assets",is.toString());
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
Log.v("Tag assets", out.toString());
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
// Log.v("Tag",out.toString());
out.write(buffer, 0, length);
// Log.v("Tag",out.toString());
}
// Log.v("Tag","Database created");
is.close();
out.flush();
out.close();
}

Android - Copy assets to internal storage

Good day!
I have just started developing for android. In my app, I need to copy the items in my assets folder to the internal storage.
I have searched a lot on SO including this which copies it to the external storage.
How to copy files from 'assets' folder to sdcard?
This is what I want to achieve:
I have a directory already present in the internal storage as X>Y>Z. I need a file to be copied to Y and another to Z.
Can anyone help me out with a code snippet? I really don't have any idea how to go on about this.
Sorry for my bad English.
Thanks a lot.
Use
String out= Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(out, Filename);
After Editing in your ref. Link Answer.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(outDir, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private 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);
}
}
I did something like this. This allows you to copy all the directory structure to copy from Android AssetManager.
public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
{
File sd_path = Environment.getExternalStorageDirectory();
String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
File dest_dir = new File(dest_dir_path);
createDir(dest_dir);
AssetManager asset_manager = getApplicationContext().getAssets();
String[] files = asset_manager.list(arg_assetDir);
for (int i = 0; i < files.length; i++)
{
String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
String sub_files[] = asset_manager.list(abs_asset_file_path);
if (sub_files.length == 0)
{
// It is a file
String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
copyAssetFile(abs_asset_file_path, dest_file_path);
} else
{
// It is a sub directory
copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
}
}
return dest_dir_path;
}
public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
{
InputStream in = getApplicationContext().getAssets().open(assetFilePath);
OutputStream out = new FileOutputStream(destinationFilePath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
public String addTrailingSlash(String path)
{
if (path.charAt(path.length() - 1) != '/')
{
path += "/";
}
return path;
}
public String addLeadingSlash(String path)
{
if (path.charAt(0) != '/')
{
path = "/" + path;
}
return path;
}
public void createDir(File dir) throws IOException
{
if (dir.exists())
{
if (!dir.isDirectory())
{
throw new IOException("Can't create directory, a file is in the way");
}
} else
{
dir.mkdirs();
if (!dir.isDirectory())
{
throw new IOException("Unable to create directory");
}
}
}
try this below code
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getExternalFilesDir(null), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private 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);
}
}
This is my Kotlin solution with auto-closable streams to copy in internal app storage:
val copiedFile = File(context.filesDir, "copied_file.txt")
context.assets.open("original_file.txt").use { input ->
copiedFile.outputStream().use { output ->
input.copyTo(output, 1024)
}
}
My small solution on Kotlin, for copy data from assets to INTERNAL STORAGE
fun copy() {
val bufferSize = 1024
val assetManager = context.assets
val assetFiles = assetManager.list("")
assetFiles.forEach {
val inputStream = assetManager.open(it)
val outputStream = FileOutputStream(File(context.filesDir, it))
try {
inputStream.copyTo(outputStream, bufferSize)
} finally {
inputStream.close()
outputStream.flush()
outputStream.close()
}
}
}
public void addFilesToSystem(String sysName, String intFil, Context c){
//sysName is the name of the file we have in the android os
//intFil is the name of the internal file
file = new File(path, sysName + ".txt");
if(!file.exists()){
path.mkdirs();
try {
AssetManager am = c.getAssets();
InputStream is = am.open(intFil);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
Toast t = Toast.makeText(c, "Making file: " + file.getName() + ". One time action", Toast.LENGTH_LONG);
t.show();
//Update files for the user to use
MediaScannerConnection.scanFile(c,
new String[] {file.toString()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
Toast t = Toast.makeText(c, "Error: " + e.toString() + ". One time action", Toast.LENGTH_LONG);
t.show();
e.printStackTrace();
}
}
}
To add a file, call the addFilesToSystem("this_file_is_in_the_public_system", "this_file_is_in_the_assets_folder", context/this context is if you do not have the method in the Activity/
Hope it helps
You can use the Envrionment#getDataDirectory method for that. It'll give the path of the data directory of the internal storage memory. This is generally where all the app related data is stored.
Alternately, if you want to store in the root directory, you can use the Environment#getRootDirectory method for that.
If you need to copy any file from assets to the internal storage and do it only once:
public void writeFileToStorage() {
Logger.d(TAG, ">> writeFileToStorage");
AssetManager assetManager = mContext.getAssets();
if (new File(getFilePath()).exists()) {
Logger.d(TAG, "File exists, do nothing");
Logger.d(TAG, "<< writeFileToStorage");
return;
}
try (InputStream input = assetManager.open(FILE_NAME);
OutputStream output = new FileOutputStream(getFilePath())) {
Logger.d(TAG, "File does not exist, write it");
byte[] buffer = new byte[input.available()];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Logger.e(TAG, "File is not found");
} catch (IOException e) {
e.printStackTrace();
Logger.d(TAG, "Error while writing the file");
}
Logger.d(TAG, "<< writeFileToStorage");
}
public String getFilePath() {
String filePath = mContext.getFilesDir() + "/" + FILE_NAME;
Logger.d(TAG, "File path: " + filePath);
return filePath;
}

Categories

Resources