Download SQLite file programmatically - java

In my android application i'm using SQLite database.
And I need to have an option in the app to download the database file.
Because sometimes I need to view the data there , so the user will download the file and send it to me and i will browse it using SQLite browsers.
Is the doable? if yes how?
String src = "/data/data/myPackage/databases/Mydb.db";
String dest = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
copyFileOrDirectory(src , dest);
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
copyFile(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}

Usually, the SQLite database is available in the /data/data/your.applications.package/databases/database.db path.
So, you could use that path; however, I suggest that you get the Database Path in the following way:
File dbFile = getDatabasePath("dbname");
String dbPath = dbFile.getPath();
Then, you can copy the database from this folder into the folder that you desire.
Copying the database to the Downloads could simulate the "download" of the SQLite database.

Related

After create setup.exe using exe4j file writing prosses not working

I want to create log file and write some text to that file in java .I completed that task.when run jar file this code working well.but after create setup.exe using exe4j file writing process not working.any one know how to do this?
this is how I get path of jar file located directory
File f = null;
public String baseUrl() {
try {
if (f == null) {
f = new File(Register.class.getProtectionDomain().getCodeSource().getLocation().toURI().getRawPath());
}
String path = f.getParent();
return path;
} catch (URISyntaxException ex) {
System.out.println(ex);
}
return "";
}
This is my log file creating process
try {
src.Log lg = new src.Log();
lg.setAction(action);
lg.setUserName(userName);
lg.setDescription(description);
lg.setTime(date);
lg.setSyncPath(syncPath);
lg.setMethod(method);
String url = baseUrl();
System.out.println(baseUrl());
String directoryName = url + "/ResFile";
File directory = new File(directoryName);
if (!directory.exists()) {
directory.mkdir();
}
File log = new File(directoryName + "/log.txt");
if (log.exists() == false) {
log.createNewFile();
}
try (PrintWriter out = new PrintWriter(new FileWriter(log, true))) {
out.append(lg.toString());
}
} catch (Exception ex) {
System.out.println(ex);
}
If you use the "JAR in EXE" mode, your log file will end up in a temporary directory, because that's where the JAR files are extracted at run time.
To get the directory where the executable is located, you can use
System.getProperty("install4j.exeDir")

Copy directory and files from java project resource

I need to copy the directory "src" that is located in my java project, as a common resource. This "src" folder contains other subfolders and files, so I need them to be copied as well. How can I achieve something like this??
The main problem I'm facing is that I can't retrieve the absolute path of my "src" folder.
A solution would be to copy file by file but their are too much and I would like to find a better solution
Thank you
EDIT:
When the user click on "Generate" button, my app ask to the user a target location where to generate some files. This target location is where I want to copy my "src" folder with all its children. The "src" folder, as sad above, is located in my java project main folder.
If you want to extract the sources from a jar file you could start with this short example
public class UnZip {
public static void main(String argv[]) {
String destDir = "/tmp/";
String sourceJar = "your_src.jar";
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceJar)))) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
File newDestination = new File(destDir + zipEntry.getName());
if (zipEntry.isDirectory()) {
unzipDir(newDestination);
} else {
unzipFile(newDestination, zis);
}
}
} catch (IOException ex) {
System.err.println("input file coud not be read " + ex.getMessage());
}
}
private static void unzipFile(File file, final ZipInputStream zis) {
System.out.printf("extract to: %s - ", file.getAbsoluteFile());
if (file.exists()) {
System.out.println("already exist");
return;
}
int count;
try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
while ((count = zis.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
dest.write(BUFFER, 0, count);
}
dest.flush();
System.out.println("");
} catch (IOException ex) {
System.err.println("file could not be created " + ex.getMessage());
}
}
private static void unzipDir(File dir) {
System.out.printf("create directory: %s - ", dir);
if (dir.exists()) {
System.out.println("already exist");
} else if (dir.mkdirs()) {
System.out.println("successful");
} else {
System.out.println("failed");
}
}
static final int BUFFER_SIZE = 2048;
static byte[] BUFFER = new byte[BUFFER_SIZE];
}
I resolved the problem creating a zip archive of the app I need to generate. Then from my project I unzip this archive taken from resource folder and after that I open the stream of the java file I need to modify and I edit it.
This is the code, similar to SubOptimal's solution
UnzipUtility unzipper = new UnzipUtility();
InputStream inputStream = getClass()
.getResource("/template/template.zip").openConnection()
.getInputStream();
unzipper.unzip(inputStream, parentFolder.getCanonicalPath());
The UnzipUtility class is from this example: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java

How to copy file from directory to another Directory in Java

I am using JDK 6.
I have 2 folders names are Folder1 and Folder2.
Folder1 have the following files
TherMap.txt
TherMap1.txt
TherMap2.txt
every time Folder2 have only one file with name as TherMap.txt.
What I want,
copy any file from folder1 and pasted in Folder2 with name as TherMap.txt.If already TherMap.txt exists in Folder2, then delete and paste it.
for I wrote the following code.but it's not working
public void FileMoving(String sourceFilePath, String destinationPath, String fileName) throws IOException {
File destinationPathObject = new File(destinationPath);
File sourceFilePathObject = new File(sourceFilePath);
if ((destinationPathObject.isDirectory()) && (sourceFilePathObject.isFile()))
//both source and destination paths are available
{
//creating object for File class
File statusFileNameObject = new File(destinationPath + "/" + fileName);
if (statusFileNameObject.isFile())
//Already file is exists in Destination path
{
//deleted File
statusFileNameObject.delete();
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
//File is not exists in Destination path.
{
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
}
}
I call the above function in main()
//ExternalFileExecutionsObject is class object
ExternalFileExecutionsObject.FileMoving(
"C:/Documents and Settings/mahesh/Desktop/InputFiles/TMapInput1.txt",
"C:/Documents and Settings/mahesh/Desktop/Rods",
"TMapInput.txt");
While I am using FileUtils function, it showing error so I click on error, automatically new package was generated with the following code.
package org.apache.commons.io;
import java.io.File;
public class FileUtils {
public static void copyFile(File sourceFilePathObject,
File statusFileNameObject) {
// TODO Auto-generated method stub
}
}
my code not showing any errors,even it's not working.
How can I fix this.
Thanks
Use Apache Commons FileUtils
FileUtils.copyDirectory(source, desc);
Your code isn't working because in order to use the ApacheCommons solution you will have to download the ApacheCommons library found here:
http://commons.apache.org/
and add a reference to it.
Since you are using JRE 6 you can't use all the NIO file utilities, and despite everyone loving Apache Commons as a quick way to answer forum posts, you may not like the idea of having to add that utility on just to get one function. You can also use this code that uses a transferFrom method without using ApacheCommons.
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
When you upgrade to 7, you will be able to do the following
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
reference:
https://gist.github.com/mrenouf/889747
Standard concise way to copy a file in Java?

How to write to a file in WebContent directory from a class in WEB-INF/classes directory

I have a Java Class UpdateStats in WEB-INF/Classes directory of a dynamic web application.This class has a function writeLog() which writes some logs to a text file.I want this text file to be in webcontent directory.Thus everytime the function is called updates stats are written in that text file.
The problem is how to give the path of that text file in webcontent directory from within that function,which resides in WEB-INF/Classes directory.
You can get your webapp root directory from ServletContext:
String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();
Hope this helps.
You can do something like below in your servlet,
When you do getServletContext().getRealPath() and put some string argument the file will see at your webcontent location.
If you want something into WEB-INF, you can give fileName like "WEB-INF/my_updates.txt".
File update_log = null;
final String fileName = "my_updates.txt";
#Override
public void init() throws ServletException {
super.init();
String file_path = getServletContext().getRealPath(fileName);
update_log = new File(file_path);
if (!update_log.exists()) {
try {
update_log.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error while creating file : " + fileName);
}
}
}
public synchronized void update_to_file(String userName,String query) {
if (update_log != null && update_log.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(update_log, true);
fos.write((getCurrentFormattedTime()+" "+userName+" "+query+"\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
To write a file you need to know absolute path of your web content directory on server as file class require absolute path.
File f = new File("/usr/local/tomcat/webapps/abc/yourlogfile.txt");
FileOutputStream out = new FileOutputStream(f);
out.writeLog("Data");
Assumption : abc is your project name
WebContent is not any directory when you deploy application. All files under web content goes directly under project name.

Copy and rename file on different location

I have one file example.tar.gz and I need to copy it to another location with different name
example _test.tar.gz. I have tried with
private void copyFile(File srcFile, File destFile) throws IOException {
InputStream oInStream = new FileInputStream(srcFile);
OutputStream oOutStream = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream(oInStream);
while((nLength = oBuffInputStream.read(oBytes)) > 0) {
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
where
String from_path = new File("example.tar.gz");
File source = new File(from_path);
File destination = new File("/temp/example_test.tar.gz");
if(!destination.exists())
destination.createNewFile();
and then
copyFile(source, destination);
It doesn't work. The path is correct. It prints that the file exists. Can anybody help me?
Why to reinvent the wheel, just use FileUtils.copyFile(File srcFile, File destFile) , this will handle many scenarios for you
I would suggest Apache commons FileUtils or NIO (direct OS calls)
or Just this
Credits to Josh - standard-concise-way-to-copy-a-file-in-java
File source=new File("example.tar.gz");
File destination=new File("/temp/example_test.tar.gz");
copyFile(source,destination);
Updates:
Changed to transferTo from #bestss
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new RandomAccessFile(sourceFile,"rw").getChannel();
destination = new RandomAccessFile(destFile,"rw").getChannel();
long position = 0;
long count = source.size();
source.transferTo(position, count, destination);
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
There is Files class in package java.nio.file. You can use the copy method.
Example: Files.copy(sourcePath, targetPath).
Create a targetPath object (which is an instance of Path) with the new name of your file.

Categories

Resources