bufferedwriter not working in android - android

i have a file that i have stored in my assets folder. i read the file and attach certain data to the file as per the user requirement. i then store the file into my emulator into the data directory. i am using bufferedwriter for this purpose but it is not working and the resultant file made in the data folder has size 0kb. the file is being made.
here is my code
InputStream myInput = this.getAssets().open("exportformat.txt");
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(myInput));
String outFileName = "/data/data/packagename/attachment.txt";
OutputStream myOutput = new FileOutputStream(outFileName);
BufferedWriter outStream = new BufferedWriter(
new OutputStreamWriter(myOutput));
String datafromfile;
while ((datafromfile = inputStream.readLine()) != null) {
StringBuffer sb = new StringBuffer(datafromfile);
if (datafromfile.equals("DTSTART:"))
sb.append(details[2]);
if (datafromfile.equals("DTEND:"))
sb.append(details[3]);
if (datafromfile.equals("SUMMARY:"))
sb.append(details[0]);
if (datafromfile.equals("DESCRIPTION:"))
sb.append(details[1]);
datafromfile = sb.toString();
outStream.write(datafromfile);
outStream.newLine();
}
// Close the streams
myOutput.flush();
myOutput.close();
outStream.close();
inputStream.close();
myInput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
i have tried debugging. the data is being correctly read , it is only the write operation that is not working.
thank you in advance.
ANSWER:
the following code is working:
InputStream myInput = this.getAssets().open("exportformat.txt");
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(myInput));
String outFileName = "/data/data/com.helios.NauticDates/attachment.ics";
File checkfile = new File(outFileName);
if(checkfile.exists()){
checkfile.delete();
}
for(int i =0 ;i<4;i++){
if(details[i].equals("null"))
details[i]=" ";
}
FileOutputStream myOutput = new FileOutputStream(outFileName);
String datafromfile;
while ((datafromfile = inputStream.readLine()) != null) {
StringBuffer sb = new StringBuffer(datafromfile);
if (datafromfile.equals("DTSTART:"))
sb.append(details[2]);
if (datafromfile.equals("DTEND:"))
sb.append(details[3]);
if (datafromfile.equals("SUMMARY:"))
sb.append(details[0]);
if (datafromfile.equals("DESCRIPTION:"))
sb.append(details[1]);
if(datafromfile.equals("CATEGORIES:"))
sb.append(details[4]);
datafromfile = sb.toString();
datafromfile+="\n";
byte[] temp = datafromfile.getBytes();
myOutput.write(temp);
}
// Close the streams
myOutput.flush();
myOutput.close();
inputStream.close();
emailintent.putExtra(Intent.EXTRA_STREAM,Uri.parse(outFileName));
emailintent.setType("plain/text");
startActivity(Intent.createChooser(emailintent, "Send mail..."));
} catch (Exception e) {
e.printStackTrace();
}

Try using a FileWriter instead of a FileOutputStream like so:
FileWriter myOutput = new FileWriter(outFileName);
BufferedWriter outStream = new BufferedWriter(myOutput);

I have a code in which I am copying sqlite database from assets folder to the android system's data folder.
private String DB_PATH =mycontext.getPackageName() + "/databases/";
private static String DB_NAME = "PartyDetails.sqlite";
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(outfilename);
// transfer byte to inputfile to outputfile
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();
}
Hope it helps :-)

Related

Loading database from asset folder - Fileoutputstream fails

My problem is that my application always fails when the database is copied from asset folder to the phone path:
/data/data/at.atn.android/databases/
MY databasename:
atnRoutenplaner.sqlite3
My code for the transfer:
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
File sampleFile = new File(outFileName);
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
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();
}
try this,
public void CopyDataBaseFromAsset() throws IOException{
InputStream in = ctx.getAssets().open("mycontacts");
Log.e("sample", "Starting copying" );
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/com.copy.copydatabasefromasset/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}

How to copy another database apps to SDCard

I've install an application to my device. But i want to copy that database to SDcard to be used by my apps. I used this code to copy database. But it's failed. And need "su" command
public void copydatabase() throws IOException{
String [] cmd1 = { "su", "cp", "/data/data/com.apps/databases/data01.db", "/mnt/extSdCard/data01.db"};
Process process = new ProcessBuilder(cmd1).start();
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any some code to copy that to SDCard without "su" command??
public static void copyDataBase(Context mActivity) throws IOException {
InputStream myInput = new FileInputStream(
new File("/data/data/" + mActivity.getPackageName()
+ "/databases/" + "xyz.sqlite"));
File files = new File("/sdcard/files/");
files.mkdirs();
String outFileName = "/sdcard/files/xyz.sqlite";
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int bufferLength;
while ((bufferLength = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, bufferLength);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
I hope its useful to you...

Android - Copying Database from Assets

Here is the code I am using (found in many answers):
InputStream myInput;
try {
myInput = iNezamApplication.getAppContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e1) {
e1.printStackTrace();
}
However, I always get an exception after reaching the OutpoutStream line:
java.io.FileNotFoundException: /data/data/package_name/databases/databasename.db: open failed: ENOENT (No such file or directory)
I tried something like this..
final String[] sample_dbName = {"DrugsNew.db"};
int assetDbSize = sample_dbName.length;
File databaseFile = new File( "/data/data/com.handyrep2.ui/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
for(int i=0;i<assetDbSize;i++){
String outFilename =null;
outFilename = "/data/data/com.handyrep2.ui/databases"+ "/" + sample_dbName[i];
File sampleFile = new File(outFilename);
try {
InputStream in = activity.getAssets().open("offlinedb/"+sample_dbName[i]);
OutputStream out = new FileOutputStream(outFilename);
// Transfer bytes from the sample input file to the sample output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
// Close the streams
out.close();
in.close();
}catch(IOException e) {
}
}
Is "package_name" a substitute for your real package name just to post it here or do really use this in your DB_PATH? :)
you must create a File object at first

How to read preexisting database into Android using ORMLite

I want to use preexisting database file using ORMLite in android. I have database.db file of already creted database. I want to use it in my app.
My class extends OrmLiteSqliteOpenHelper.
Can any one have an idea? Please help
I use to copy database file into data path using
public static void copyDataBase(String path,Context c) throws IOException{
//Open your local db as the input stream
InputStream myInput = c.getAssets().open("Mydb.db");
// Path to the just created empty db
String outFileName = "/data/data/packageName/databases/databaseName";
String outFileName2 = "/data/data/packageName/databases/";
File file = new File(outFileName2);
if(!file.exists())
file.mkdirs();
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
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();
}
But it wont help me .
This is kind of a stab in the dark since I do not know what your exact problem is, but can't you just specify the database file (and path) in the OrmLiteSqliteOpenHelper constructor?
OrmLiteSqliteOpenHelper(android.content.Context context, String databaseName, android.database.sqlite.SQLiteDatabase.CursorFactory factory, int databaseVersion)
Also there are a number of questions on this forum that deal with opening custom database files. This question is not ORMLite specific but they might get you forward since it open a custom database file.
Hope this help you a bit on your way.
I have solved the problem by below implementation
try {
String destPath = "/data/data/" + context.getPackageName()
+ "/databases";
Log.v("LOG", destPath);
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
File outputFile = new File("/data/data/"
+ context.getPackageName() + "/databases",
"Name ofyour Database");
outputFile.createNewFile();
String DatabaseFile = "database file name from asset folder";
InputStream in = context.getAssets().open(DatabaseFile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
Log.v("TAG", "ioexeption");
e.printStackTrace();
}

SQLiteException when copying/decompressing a zipped DB onto Android

Currently, I am copying a database from my assets folder to the to the /data/data/package folder. This is that code (from the answer here), which works:
public void copyDataBase() throws IOException{
// open db as input stream
InputStream myInput;
//open empty db as output stream
OutputStream myOutPut;
try {
myInput = myContext.getAssets().open(DB_NAME);
//path to newly created db
String outFileName =DB_PATH + DB_NAME;
myOutPut = new FileOutputStream(outFileName);
//transfer bytes from the inputFile to the outPutFile
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer))>0){
myOutPut.write(buffer, 0, length);
}
myOutPut.flush();
myOutPut.close();
myInput.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now in order to save space in the .apk download, I am trying to zip the file before copying it to the /data/data/package folder.
private void copyDataBaseFromZipFile() {
InputStream inputStream = null;
OutputStream outputStream = null;
String sourcePathname = this.getBundledPathname();
String destinationPath = this.getDatabasePathname();
try {
inputStream = this.mContext.getAssets().open(sourcePathname);
ZipInputStream zipStream = new ZipInputStream(inputStream);
int BUFFER = 8096;
outputStream = new FileOutputStream(destinationPath);
BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER);
ZipEntry entry;
while ((entry = zipStream.getNextEntry()) != null) {
if (entry.getName().equals("androidDB.sql")) }
int count;
byte data[] = new byte[BUFFER];
while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
}
outputStream.flush();
outputStream.close();
dest.flush();
dest.close();
zipStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When I attempt to open the database later (with SQLiteDatabse), I get this error: android.database.sqlite.SQLiteException: unable to open database file
I haven't changed anything except the file I'm copy from, which is only a zipped version of the one I was previously copying over. The final database is the right size, so it doesn't seem to be still compressed... If anyone has any suggestions or possible reasons WHY it won't open, it would be greatly appreciated.
You should remove these lines:
outputStream.flush();
outputStream.close();
Your BufferedOutputStream probably has some buffered bytes, but since you close outputStream before you call dest.flush(), those bytes are never actually written to the file.

Categories

Resources