The library I'm using requires me to pass it a file path.
Currently, I use the Uri to create a new file (in an AsyncTask) as shown below:
#Override
protected String doInBackground(Uri... params) {
File file = null;
int size = -1;
try {
try {
if (returnCursor != null && returnCursor.moveToFirst()){
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
size = (int) returnCursor.getLong(sizeIndex);
}
}
finally {
if (returnCursor != null)
returnCursor.close();
}
if (extension == null){
pathPlusName = folder + "/" + filename;
file = new File(folder + "/" + filename);
}else {
pathPlusName = folder + "/" + filename + "." + extension;
file = new File(folder + "/" + filename + "." + extension);
}
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = bis.read(data)) != -1) {
if (!isCancelled()) {
total += count;
if (size != -1) {
publishProgress((int) ((total * 100) / size));
}
fos.write(data, 0, count);
}
}
fos.flush();
fos.close();
} catch (IOException e) {
errorReason = e.getMessage();
}
return file.getAbsolutePath();
}
As you can imagine, this might take some time depending on the file size.
Question
Is there any way to access the file without having to create/copy it?
*I have read that I can use ContentResolver and methods like openInputStream() and openOutputStream(). But this will only provide me with a stream and does not solve the issue I have of having to write a new file?
Extra info:
I get the Uri by passing the following to an Intent:
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
Then in onActivityResult I get the Uri by calling data.getData().
Please do not provide me with solutions like this one. I do not want to get a file Uri from a content Uri because it's unreliable and incorrect.
It looks pretty clear that a library that cannot handle a content scheme is of no use if you only have a content scheme.
You have to make a copy of the content in a file. As you do now.
Related
I am trying to make a save to gallery feature for my app. My app's minimum api level is 21 and max 30.
Here is the code I am using for saving video to gallery. Everything works perfect but the code only works for API 29 and Above. Here is the code:
String videoFileName = "video_" + System.currentTimeMillis() + ".mp4";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues valuesvideos;
valuesvideos = new ContentValues();
valuesvideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "Folder");
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesvideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 1);
ContentResolver resolver = context.getContentResolver();
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri uriSavedVideo = resolver.insert(collection, valuesvideos);
ParcelFileDescriptor parcelFileDescriptor;
try {
assert uriSavedVideo != null;
parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
assert parcelFileDescriptor != null;
FileOutputStream out = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
FileInputStream in = new FileInputStream(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES) + File.separator + "Application" + File.separator + "video.mp4");
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
parcelFileDescriptor.close();
} catch (Exception e) {
e.printStackTrace();
}
valuesvideos.clear();
valuesvideos.put(MediaStore.Video.Media.IS_PENDING, 0);
context.getContentResolver().update(uriSavedVideo, valuesvideos, null, null);
}
This is the code I use for Versions below API 29:
ContentValues valuesvideos;
valuesvideos = new ContentValues();
valuesvideos.put(MediaStore.Video.Media.DATA, context.getExternalFilesDir(Environment.DIRECTORY_MOVIES) + File.separator + "Folder");
valuesvideos.put(MediaStore.Video.Media.TITLE, videoFileName);
valuesvideos.put(MediaStore.Video.Media.DISPLAY_NAME, videoFileName);
valuesvideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesvideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
ContentResolver resolver = context.getContentResolver();
Uri collection = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
Uri uriSavedVideo = resolver.insert(collection, valuesvideos);
ParcelFileDescriptor parcelFileDescriptor;
try {
assert uriSavedVideo != null;
parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uriSavedVideo, "w");
assert parcelFileDescriptor != null;
FileOutputStream out = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
FileInputStream in = new FileInputStream(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES) + File.separator + "Application" + File.separator + "video.mp4");
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
parcelFileDescriptor.close();
} catch (Exception e) {
e.printStackTrace();
}
valuesvideos.clear();
context.getContentResolver().update(uriSavedVideo, valuesvideos, null, null);
How to write this exact function for lower APIs? Now I have tried MediaScanner but it seems too slow and I can't get the uri of the saved file. Hope you will answer. Regards.
I've created a pretty simple Java GUI to browse/load a zip file on Windows platform to begin unzipping and then do some file checking.
Everything works fine except that I have to close the GUI window in order to delete the zip file that has been opened in the GUI.In my finally block of the unzipping method, I've tried adding the following:
public static String unZip(String path)
{
int count = -1;
String savepath = "";
File file = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
savepath = path.substring(0, path.lastIndexOf("\\")) + File.separator; //File saving directory
new File(savepath).mkdir(); //create the saving directory
ZipFile zipFile = null;
String topLevelDirName="";
try
{
zipFile = new ZipFile(path,Charset.forName("gbk")); //Encoding
Enumeration<?> entries = zipFile.entries();
int levelCount=0;
while(entries.hasMoreElements())
{
byte buf[] = new byte[buffer];
ZipEntry entry = (ZipEntry)entries.nextElement();
String filename = entry.getName();
boolean ismkdir = false;
if(filename.lastIndexOf("/") != -1){ //To check if there is a directory
ismkdir = true;
}
filename = savepath + filename;
if(entry.isDirectory()){ //If it is a directory
levelCount++;
file = new File(filename);
file.mkdirs();
if(levelCount==1)
topLevelDirName = filename;
continue;
}
file = new File(filename);
if(!file.exists()){
if(ismkdir){
new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs();
}
}
file.createNewFile(); //Create the file
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while((count = is.read(buf)) > -1)
{
bos.write(buf, 0, count);
}
bos.flush();
bos.close();
fos.close();
is.close();
}
zipFile.close();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
if(bos != null){
bos.close();
}
if(fos != null) {
fos.close();
}
if(is != null){
is.close();
}
if(zipFile != null){
zipFile.close();
}
}catch(Exception e) {
e.printStackTrace();
}
return topLevelDirName;
}
}
However, I am still not able to delete the zip unless explicitly close the GUI.
Wonder if there is anything to do with the Windows file handle?Thanks in advance.
Java 8 introduced the try-with-resources Statement to make this kind of situation simpler and cleaner.
One of the issues you have is, if any one of the attempts to close the many resources you have open fails, then none of the others will be closed
public static String unZip(String path) throws IOException {
int count = -1;
File sourceFile = new File(path);
String name = sourceFile.getName();
name = name.substring(0, name.lastIndexOf(".zip"));
File sourcePath = new File(sourceFile.getParent(), name);
System.out.println("SavePath = " + sourcePath);
if (!sourcePath.exists() && !sourcePath.mkdirs()) {
throw new IOException("Could not create directory " + sourcePath);
}
String topLevelDirName = "";
try (ZipFile zipFile = new ZipFile(sourceFile)) {
Enumeration<?> entries = zipFile.entries();
int levelCount = 0;
byte buf[] = new byte[1024];
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String filename = entry.getName();
File file = new File(sourcePath, filename);
if (entry.isDirectory()) { //If it is a directory
levelCount++;
System.out.println("Make directory " + file);
if (!file.exists() && !file.mkdirs()) {
throw new IOException("Could not create directory " + filename);
}
} else {
System.out.println("Extract to " + file);
try (InputStream is = zipFile.getInputStream(entry);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
}
}
}
}
return topLevelDirName;
}
I've update the code slightly to try and make it a little cleaner and simpler and to take advantage of the available APIs
The method I wrote to download files always produce corrupted files.
public static String okDownloadToFileSync(final String link, final String fileName, final boolean temp, DownloadStatusManager statusManager, ErrorDisplayerInterface errorDisplayerInterface) {
Request request = new Request.Builder()
.url(link)
.build();
OkHttpClient client = Api.getInstance().getOkHttpClient();
OutputStream output = null;
InputStream input = null;
try {
Response response = client.newCall(request).execute();
//Add the file length to the statusManager
final int contentLength = Integer.parseInt(response.header("Content-Length"));
if (statusManager != null) {
statusManager.add(Hash.md5(link), contentLength);
}
//Get content type to know extension
final String contentType = response.header("Content-Type");
final String ext = contentTypeMap.get(contentType);
Log.i(TAG, link + "\n --> contentType = " + contentType + "\n --> ext = " + ext);
if (ext == null) {
Log.e(TAG, "-----------\next is null, seems like there is a problem with that url : \n " + link + "\n----------");
return null;
} else if (ext.equals("json")) {
Log.e(TAG, "-----------\ndownloadable file seems to be a json, seems like there is a problem with that url : \n " + link + "\n----------");
return null;
}
//Check if file already exists
if (!temp && fileName != null) {
File test = new File(M360Application.getContext().getFilesDir(), fileName + "." + ext);
if (test.exists()) {
Log.i(TAG, "File exists ! : " + test.getPath());
test.delete();
//return test.getAbsolutePath();
}
}
// expect HTTP 200 OK, so we don't mistakenly save error report instead of the file
if (!response.isSuccessful()) {
errorDisplayerInterface.popWarn(null, "Error while downloading " + link, "connection.getResponseCode() != HttpURLConnection.HTTP_OK");
return null;
}
input = response.body().byteStream();
File file;
if (temp) {
file = File.createTempFile(UUID.randomUUID().toString(), ext, M360Application.getContext().getCacheDir());
} else {
file = new File(M360Application.getContext().getFilesDir(), fileName + "." + ext);
}
output = new FileOutputStream(file);
output.write(response.body().bytes());
// byte data[] = new byte[4096];
// long total = 0;
// int count;
// while ((count = input.read(data)) != -1) {
// output.write(data, 0, count);
// total++;
//
// if (statusManager != null) {
// statusManager.update(Hash.md5(link), contentLength - total);
// }
// }
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
errorDisplayerInterface.popError(null, e);
} finally {
if (statusManager != null) {
statusManager.finish(Hash.md5(link));
}
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
return null;
}
I access these file via adb, transfer them to my sccard, and there I see that they seem to have the proper size, but has no type according to for instance Linux file command.
Would you know what is missing and how to fix it?
Thank you.
Edit
Simpler version of the code ( but the bug is the same )
public static String okioDownloadToFileSync(final String link, final String fileName) throws IOException {
Request request = new Request.Builder()
.url(link)
.build();
OkHttpClient client = Api.getInstance().getOkHttpClient();
Response response = client.newCall(request).execute();
final int contentLength = Integer.parseInt(response.header("Content-Length"));
//Get content type to know extension
final String contentType = response.header("Content-Type");
final String ext = contentTypeMap.get(contentType);
// expect HTTP 200 OK, so we don't mistakenly save error report instead of the file
if (!response.isSuccessful()) {
return null;
}
File file = new File(M360Application.getContext().getFilesDir(), fileName + "." + ext);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
Log.i(TAG, "file.length : " + file.length() + " | contentLength : " + contentLength);
return file.getAbsolutePath();
}
The log : file.length : 2485394 | contentLength : 1399242
Solution
The problem was that I was getting the OkHttpClient from my API singleton, which was used by retrofit and had multiples interceptors. Those interceptors were polluting the response.
So I OkHttpClient client = Api.getInstance().getOkHttpClient(); became OkHttpClient client = new OkHttpClient.Builder().build(); and everything is now ok !
Thanks a lot. I'm dividing the method into smaller pieces right now.
Instead of
output.write(response.body().bytes());
try something like this
byte[] buff = new byte[1024 * 4];
while (true) {
int byteCount = input.read(buff);
if (byteCount == -1) {
break;
}
output.write(buff, 0, byteCount);
}
How do I copy all .jpgs from a folder over to another folder using FileInputStream?
At the moment I have it as this for copying my picture over to my SMB share:
protected String doInBackground(String... params) {
File file = new File("/sdcard/Data/pics/IMG.jpg");
String filename = file.getName();
NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(
servername, username, password);
try {
SmbFile sfile = new SmbFile(servername + "/" + filename, auth1);
if (!sfile.exists())
sfile.createNewFile();
sfile.connect();
InputStream in = new FileInputStream(file);
SmbFileOutputStream sfos = new SmbFileOutputStream(sfile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) >= 0) {
sfos.write(buf, 0, len);
}
in.close();
sfos.close();
z = "File copied successfully";
} catch (Exception ex) {
z = z + " " + ex.getMessage().toString();
}
return z;
}
}
I had used lambdas before, like this:
File file = new File(("/sdcard/Data/pics);
File[] jpgFiles = file.listFiles((dir, name) -> name.endsWith(".jpg"));
for (File entry : jpgFiles) {
System.out.println("File: " + entry.getName());
}
but since my program also should support older versions of Android I can't use it.
I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.
while ((ret = input.read(imageCharArray)) != -1) {
packet.append(new String(imageCharArray, 0, ret));
totRead += ret;
imageCharArray = new char[4096];
}
file = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
PrintWriter printWriter = new PrintWriter(file);
// outputStream = new FileOutputStream(file); //also Used FileoutputStream for writting
// outputStream.write(packet.toString().getBytes());//
// ,
printWriter.write(packet.toString());
// outputStream.close();
printWriter.close();
}
I have also tried FileoutputStream but hardlucj for this too as commented in my code.
Edit
I have used this also. I have a content length field upto which i am reading and writing
byte[] bytes = new byte[1024];
int totalReadLength = 0;
// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
&& contentLength >= (totalReadLength)) {
outputStream.write(bytes, 0, read);
totalReadLength += read;
System.out.println(" read size ======= "
+ read + " totalReadLength = "
+ totalReadLength);
}
String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
total += count;
out.write(buffer, 0, count);
}
I tested it in my Nexus4 and it's working for me. Here is the snippet of code what I tried :
public void saveImage(String urlPath)throws Exception{
String fileName = "kumar.jpg";
File folder = new File("/sdcard/MyImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder,
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just Call the above function in a background thread and pass your url. It'll work for sure. Let me know if it helps.
You can check below code.
destinationFile = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[1024];
int i;
for (long l = 0L; (i = input.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();