android copy database from assets folder - java

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

Related

How copy Assets folder to internal storage?

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) { }
}

How to solve this Close this "FileOutputStream"

How to solve this?
I am getting the below error : Close this "FileOutputStream". but i have closes it already in finally block
public void initHistoryForOldFile(File oldFile, String filePath) throws PIDException {
InputStream inStream = null;
OutputStream outStream = null;
try {
File historyFile = new File(StringUtil.append(filePath, File.separator, "history"));
FileUtils.ensureDirectory(historyFile);
File oldHistoryFile = new File(StringUtil.append(filePath, File.separator, "history", File.separator, oldFile.getName()));
oldHistoryFile.createNewFile();
if (oldFile.exists()) {
inStream = new FileInputStream(oldFile);
outStream = new FileOutputStream(oldHistoryFile);
byte[] buffer = new byte[PIDConstants.IMAGE_FILE_SIZE_LIMIT];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
oldFile.delete();
}
} catch (IOException e) {
LOGGER.error("Exception occured in historyUpdateForOldFIle", e);
} finally {
if (null != inStream) {
try {
inStream.close();
} catch (IOException e) {
LOGGER.error("Exception occured whole closing inStream", e);
}
}
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
LOGGER.error("Exception occured whole closing outStream", e);
}
}
}
}
If using java 7
You can use Try with resources
try(InputStream inStream = new FileInputStream(oldFile)){}
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.
try(InputStream instream = new fileinputstream(oldFile)){};

Copy the dynamically incrementing log file data from FTP to local

I need to copy and paste dynamically incrementing log file data from FTP Server to local drive.
The below program I used can only do the copying one time. And not in the incremental manner.
public class ReadFtpFile {
public static void main(String[] args) throws UnknownHostException {
String server = "myIP";
int port = 20;
String user = "username";
String pass = "password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #2: using InputStream retrieveFileStream(String)
String remoteFile2 = "/folder/myfile.log";
File downloadFile2 = new File("F:/myfolder/mylogfile.log");
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream2.write(bytesArray, 0, bytesRead);
}
Boolean success = ftpClient.completePendingCommand();
if (success) {
System.out.println("File #2 has been downloaded successfully.");
}
outputStream2.close();
inputStream.close();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
The log file data in the FTP server is growing for every second.I need to update the local file with new data in the FTP.
Replace the lines
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
with
ftpClient.setRestartOffset(downloadFile2.length());
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2, true));
This will check if the file already exists and, if so, download only the new data. If you need to do this periodically, add a loop around the whole try-catch block.
You need to update your code with Java threads and combine while loops to schedule this program for desired time.
String remoteFile2 = "/folder/myfile.log";
File downloadFile2 = new File("F:/myfolder/mylogfile.log");
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
byte[] bytesArray = new byte[4096];
int bytesRead = -1;
int minutecount=0;
while(minutecount==120){
while ((bytesRead = inputStream.read(bytesArray)) != -1) {
outputStream2.write(bytesArray, 0, bytesRead);
}
// Here i sceduled for every 1 minute
Thread.sleep(60*1000);
minutecount++;
}
Boolean success = ftpClient.completePendingCommand();
if (success) {
System.out.println("File #2 has been downloaded successfully.");
}
outputStream2.close();
inputStream.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;
}

Copy Files from Internal Storage to external storage

Im trying to use Adobe reader to read pdf files downloaded from the server the problem is When i store it in the internal storage Other application can't read the file. Now i Want to know how can i Copy this file in the external storage(/sdcard/) so it can be viewed by pdf viewers.
Due to security reason I'm storing the files in the Internal Storage and would delete the one in external storage afterwards.
My question is How can i copy the file saved in the internal storage without using the raw or the assets to put in the inputstream.
InputStream myInput = getResources().openRawResource(R.raw.p13);
FileOutputStream fos = openFileOutput("sample", Context.MODE_PRIVATE);
// transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
fos.write(buffer, 0, length);
}
// Close the streams
fos.flush();
fos.close();
myInput.close();
at which path you are storing the pdf file ?
See below one to get file from android Assets and copy it to the specific sdcard location.
I will first check for the pdf file whether it is already available at desire path or not.
File file1 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_Molding.pdf");
File file2 = new File("/sdcard/SampleProjectApp/WindsorONE_Mobile_PK.pdf");
File file3 = new File("/sdcard/SampleProjectApp/Alone.mp4");
if(!((file1.exists())) || !((file2.exists())) || !((file3.exists()))) {
ArrayList<String> files = new ArrayList<String>();
files.add("WindsorONE_Mobile_Molding.pdf");
files.add("WindsorONE_Mobile_PK.pdf");
files.add("Alone.mp4");
new myAsyncTask().execute(files);
}
Now, if the file is not present at that position then it will execute the myAsyncTask to copy file from assets to the SdCard.
// AsyncTass for the Progress Dialog and to do Background Process
private class myAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ListSample.this, "W1 SALES (beta)", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileFromAssetsToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file from Assets to the SDCard
public void copyFileFromAssetsToSDCard(String fileFromAssets){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFromAssets);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/SampleProjectApp", fileFromAssets));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
Updated
For your part:
replace
SampleProjectApp/WindsorONE_Mobile_Molding.pdf
with
Android/data/com.project.projectname/cache/YOUR_PDF_FILE.pdf
Hope it make sense.
Updated 2
Below code is copy file from one path to another path. You simply have to pass the path of the file where it is exist and the path where it has to be copy.
Code:
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;
}
}
you can use this method
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
InputStream in = null;
OutputStream out = null;
in = //Place your file in the inputstream
out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + filename);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
}
else
{
Toast.makeText(getApplicationContext(), "SD Card not present", Toast.LENGTH_LONG).show();
}

Categories

Resources