I have a custom method to
copy the database from assets folder to the database directory
AssetManager am = myContext.getAssets();
OutputStream os = new FileOutputStream(DBFile);
DBFile.createNewFile();
byte []b = new byte[1024];
int i, r;
String []Files = am.list("");
Arrays.sort(Files);
for(i=1;i<5;i++) {
String fn = String.format("0%d.database", i);
if(Arrays.binarySearch(Files, fn) < 0)
break;
InputStream is = am.open(fn);
while((r = is.read(b)) != -1)
os.write(b, 0, r);
is.close();
}
os.close();
All works as expected and the database is copied to the apps database directory
except for when I change the android system language (settings>language) and set
the system language as arabic, and re install the app, it crashes and the database
file isn't copied to the databases directory. It's just a blank file.
Im thinking maybe i should read the database file with an encoding specified
because something must change in java dhe moment I change the language.
Related
I am trying to retrieve a zip from my database, but each time the generated zip is corrupted. The zip is supposed to contain 3 pdf files, but when I generate it, it only contains the first one with size 0 and when I try to open the zip "Unexpected end of archive" error popup is displayed. I cannot figure out what's wrong, as the file in the database is not corrupted and the code is working in my PC, and many other remote servers, but not on a specific remote server (all run on wildfly 10, same mysql database configuration, with the same zip stored in database). My code is the following (JDBC):
...
Statement stmt = conn.createStatement();
ResultSet rsstmt.executeQuery("SELECT document_data from table "
+ "WHERE condition");
if (rs.next() && rs.getBytes("document_data") != null) {
ByteArrayInputStream(rs.getBytes("document_data"));
File zipped= new File("exported.zip");
FileOutputStream fos = new FileOutputStream(zipped);
byte[] buffer = new byte[1];
InputStream is = rs.getBinaryStream(1);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
I tried the following code too, but didn't work either:
InputStream in = null;//zip bytes
OutputStream out;//zip archive to be generated
.
.
.
if (rs.next() && rs.getBytes("document_data") != null) {
in = new ByteArrayInputStream(rs.getBytes("document_data"));
}
out = new FileOutputStream("exported.zip");
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
When executing the following SQL query, the zip generated is NOT corrupted:
SELECT document_data INTO DUMPFILE '/tmp/exported.zip' FROM table WHERE condition;
NOTE: The zip size in database(LONGBLOB field) is 830K.
NOTE: I tried with JDBC and Hibernate, but result is the same.
Any ideas on this strange behavior?
You are both calling getBytes(), which reads out the blob, and then reading from its input stream, which by this stage will be empty.
Get rid of the getBytes() call.
I am trying to transfer a SQLite database into an app by downloading it and then unzipping it to the correct location. I was successful in transferring the DB when it was unzipped. The error I get is that it cannot find any of the tables I query. I have also been successful in unzipping and reading normal text files.
The DB has Hebrew and English, but that has not caused problems before. The bilingual DB was copied successfully when it was not zipped and bilingual texts have been successfully unzipped and read. Still, it is a possibility that there is an encoding problem going on. That seems weird to me, because as you can see below in the code, I'm just copying the bytes directly.
-EDIT-
Let's say the prezipped db is called test1.db. I zipped it, put it in the app, unzipped it and called that test2.db. when I ran a diff command on these two, there were no differences. So there must be a technical issue with the way android is reading the file / or maybe encoding issue on android that doesn't exist on pc?
I hate to do a code dump, but i will post both my copyDatabase() function (which works). That is what I used previously running it on an unzipped DB file. I put it here as comparison. Now I'm trying to use unzipDatabase() function (which doesn't work), and use it on a zipped DB file. The latter function was copied from How to unzip files programmatically in Android?
private void copyDatabase() throws IOException{
String DB_NAME = "test.db";
String DB_PATH = "/data/data/org.myapp.myappname/databases/";
//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 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();
}
private boolean unzipDatabase(String path)
{
String DB_NAME = "test.zip";
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = myContext.getAssets().open(DB_NAME);
zis = new ZipInputStream(is);
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
// write to a file
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
Log.d("yo",path + filename);
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
OutputStream fout = new FileOutputStream(path + filename);
// reading and writing zip
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.flush();
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
So still don't know why, but the problem is solved if I first delete the old copy of the database (located at DB_PATH + DB_NAME) and then unzip the new one there. I didn't need to do this when copying it directly.
so yay, it was a file overwriting issue...If someone knows why, feel free to comment
The below code is used to zip normal text file. When I extract using WinRaR its showing the content properly, but when I open with Windows Explorer its empty, no file listed. I am using Windows 7 Enterprise (64 bit) operating system. Any idea why its not listing in Windows explorer? Thanks in advance.
File file = new File("F:\\sample.txt");
byte[] buf = new byte[1024];
String outFilename = "F:\\zipped_sample.zip";
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
FileInputStream in = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.toString()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
out.flush();
}
out.closeEntry();
out.close();
in.close();
} catch (Exception e) {
// log exception here
}
ZipEntry constructor takes name but you are providing it a path by doing file.toString(); Try:
New ZipEntry(file.getName());
This will pass the file name.
i had the same problem zip file were not extracted and was shown as empty the problem was in the folder names in zip file. If folder name consist of > or < symbols i saw the failure . SO in the code new ZipEntry(file.toString()) i try to clean up any folder names with those particular symbols
I wrote small program for downloading files via url. Every other files format I can open properly, but for downloaded pdf it's impossible.
public static void saveFile(String fileUrl, String destinationFile) throws IOException {
URL url = new URL(fileUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
os.flush();
is.close();
os.close();
}
Do I need special way for handling pdf downloads?
When I try to get selected pdf via URL in browser it's displays properly
EDIT
Added flush() to code, still no success
Trying to open damaged pdf in browser (FF) returns error:
File does not begin with '%PDF-'
Adobe Reader returns:
File could not be open because it is either not a supported file type
or because file has been damaged.
Damages pdf has smaller size (about 80%) than original
The damaged pdf files has website html code inside.
I have deployed an application in Google App Engine and and I want to upload and download data from server using java code at desktop and server code for download request and one more: Where do I store the data in apps engine?
To store binary data (file contents) you have three options:
Blob property of Datastore entities
Blobstore
Google Cloud Storage
You can save your file anywhere on your server, you just need to know the path.
how i direct it as output stream?
Here is a code snippet that can help you.
File fileOnServer = new File("Hello.txt"); // Give full path where your file is located
byte[] file = new byte[(int) fileOnServer.length()];
FileInputStream fileInputStream = new FileInputStream(fileOnServer);
fileInputStream.read(file);
int contentLength = (int) file.length;
response.setContentLength(contentLength);
response.setHeader("Content-Disposition", "attachment; filename=\"Hello.txt\"");
out = response.getOutputStream();
int bytesWritten = 0;
byte[] buffer = new byte[1024];
while (bytesWritten < contentLength) {
int bytes = Math.min(1024, contentLength - bytesWritten);
System.arraycopy(file, bytesWritten, buffer, 0, bytes);
if (bytes > 0) {
out.write(buffer, 0, bytes);
bytesWritten += bytes;
} else if (bytes < 0);
}
get download to user end?
Well you can add ClickHandler on a Button on your client side and override onClick method.
public void onClick(ClickEvent event) {
Window.open("UrlToYourServelet", "_blank", "null");
}
Hope this helps!
EDIT
I have found a solution. You can upload the file at any free file hosting site like this. This site provides a URL for every uploaded file. So in your servelet, make a HTTP request to the URL and download the file in byte[] and write it on outputStream as shown in the code above.