I have a database on my Android phone, and I need to get the information onto an SD card.
Is it possible to save the database file onto the SD card in a readable state? I haven't been able to find any information on how to do this.
Some source code that copies the database file to an SD card would be ideal.
The database file is just like any other file, if you make a binary file copy it will work.
Java has no built in file copy method, so you can use this:
Standard concise way to copy a file in Java?
Just don't forget to add your manifest permission to write to the SD card:
Permission to write to the SD card
Here's a script I've bastardized from several other users on SO. It looks like you can tell android where to store the file, but when you go into the phone with adb shell you might have a hard time finding it!
This code (which I mapped to a temporary button in my action bar for debugging) would print something like: "database saved to: /storage/emulated/0/DB-DEBUG/todotable.db", but going into the shell on my phone I actually found my database at: "/storage/emulated/legacy/DB-DEBUG/"... not sure what's up with that, but now I can check out my database with an sqlite browser!
//db will reside in: /storage/emulated/legacy/DB_DEBUG
private void copyDatabase(Context c, String DATABASE_NAME) {
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
InputStream myInput = null;
Log.d("testing", " testing db path " + databasePath);
Log.d("testing", " testing db exist " + f.exists());
if (f.exists()) {
try {
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DB-DEBUG");
if (!directory.exists()){
directory.mkdir();
}
String copyPath = directory.getAbsolutePath() + "/" + DATABASE_NAME;
myOutput = new FileOutputStream(copyPath);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
Toast.makeText(getBaseContext(), "Your database copied to: " + copyPath, Toast.LENGTH_LONG).show();
Log.d("testing", " database saved to: " + copyPath);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
Related
I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
This is a function I have written that tries to:
Create a folder with the users name
Save a .jpg inside of that
folder
The folder creation works fine, however when I try to save the pictures, they all save with the correct name, however they do not save in their intended folders. In other words, instead of having a folder containing a bunch of folders each containing one picture, I have one folder containing a bunch of empty folders, and a bunch of pictures all outside their folders (I can clarify if needed).
This is my code:
public void addToDir(List<Contact> list){
for(int i = 0; i < list.size(); i++){
String nameOfFolder = list.get(i).getName();
Bitmap currentBitmap = list.get(i).getBusiness_card();
String conName = Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator +
"Connected Accounts" + File.separator + nameOfFolder;
File conDir = new File(conName);
if (!conDir.mkdirs()) {
if (conDir.exists()) {
} else {
return;
}
}
try {
FileOutputStream fos = new FileOutputStream(conName + ".jpg", true);
currentBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
}
I suspect the problem is with the FileOutputStream path, but I am not sure how to set it so that it is set to the folder I just created.
Much appreciated
This is how to define mFileTemp
String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//directory : any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
This is how i save any image
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
Log.e("error save", "Error while creating temp image", e);
}
And copyStream method
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it possible to copy database file to SD card?
I have a database on my Android phone, and I need to get the information onto an SD card.
Is it possible to save the database file onto the SD card in a readable state? I haven't been able to find any information on how to do this. I know the name of the database, and fields etc...
I've found some examples that show how to save to SD cards, but not exactly what I need.
Some source code that copies the database file to an SD card would be perfect.
Hopefully this question is clear enough.
Yes. Here is the function that i use:
public void copyDBToSDCard() {
try {
InputStream myInput = new FileInputStream("/data/data/com.myproject/databases/"+DATABASE_NAME);
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
Log.i("FO","File creation failed for " + file);
}
}
OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Log.i("FO","copied");
} catch (Exception e) {
Log.i("FO","exception="+e);
}
}
For a project that I worked on, I put a menu option in the home screen that I could call this function from at any time. Then, I'd move the database to my desktop and open it up with the SQLite Manager plugin for FireFox.
Sure. If this is a database that exists in your app, you can get a reference to the db file via Context.getDatabasePath(), passing it the database name. From there, it's just a routine file copy operation:
//Get a reference to the database
File dbFile = mContext.getDatabasePath("mydb");
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
Where the method fileCopy() is defined as:
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
HTH!
Could you please suggest how to deal with these situations ? I understand that in the second example, it is very rare that it would happen on unix, is it ? If access rights are alright. Also the file wouldn't be even created. I don't understand why the IOException is there, either it is created or not, why do we have to bother with IOException ?
But in the first example, there will be a corrupted zombie file. Now if you tell the user to upload it again, the same thing may happen. If you can't do that, and the inputstream has no marker. You loose your data ? I really don't like how this is done in Java, I hope the new IO in Java 7 is better
Is it usual to delete it
public void inputStreamToFile(InputStream in, File file) throws SystemException {
OutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new SystemException("Temporary file created : " + file.getAbsolutePath() + " but not found to be populated", e);
}
boolean fileCorrupted = false;
int read = 0;
byte[] bytes = new byte[1024];
try {
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
fileCorrupted = true;
logger.fatal("IO went wrong for file : " + file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
if(fileCorrupted) {
???
}
}
}
public File createTempFile(String fileId, String ext, String root) throws SystemException {
String fileName = fileId + "." + ext;
File dir = new File(root);
if (!dir.exists()) {
if (!dir.mkdirs())
throw new SystemException("Directory " + dir.getAbsolutePath() + " already exists most probably");
}
File file = new File(dir, fileName);
boolean fileCreated = false;
boolean fileCorrupted = false;
try {
fileCreated = file.createNewFile();
} catch (IOException e) {
fileCorrupted = true;
logger.error("Temp file " + file.getAbsolutePath() + " creation fail", e);
} finally {
if (fileCreated)
return file;
else if (!fileCreated && !fileCorrupted)
throw new SystemException("File " + file.getAbsolutePath() + " already exists most probably");
else if (!fileCreated && fileCorrupted) {
}
}
}
I really don't like how this is done in Java, I hope the new IO in Java 7 is better
I'm not sure how Java is different than any other programming language/environment in the way you are using it:
a client sends some data to your over the wire
as you read it, you write it to a local file
Regardless of the language/tools/environment, it's possible for the connection to be interrupted or lost, for the client to go away, for the disk to die, or for any other error to occur. I/O errors can occur in any and all environments.
What you can do in this situation is highly dependent on the situation and the error that occured. For example, is the data structured in some way where you could ask the user to resume uploading from record 1000, for example? However, there is no single solution that fits all here.