I have a method that takes an image's URL and attempts to save it in memory. I need to retrieve this saved file later, and want to do so by getting its file path. How do I get the file name from this save method?
InputStream input;
try {
URL url = new URL (strURL);
input = url.openStream();
byte[] buffer = new byte[1500];
OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
try {
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
}
finally {
output.close();
buffer = null;
}
}
I am using Android Studio.
Related
I'm trying to store an audio file that is picked by the user from his own music player into sqlite database and I want to know is there a way to convert audio files to byte array.
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] arr = readByte(inputStream);
Log.d("byte: ", "" + Arrays.toString(arr));
or
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
try {
String path = ""; // Audio File path
InputStream inputStream = new FileInputStream(path);
byte[] myByteArray = getBytesFromInputStream(inputStream);
// ...
} catch(IOException e) {
// Handle error...
}
I‘m new to Android programming and couldn‘t find a good solution for my problem yet. In my App users can select photos from their gallery which are then used in a Cardview Layout for different categorys in the App which the user can create on his own. By now I‘m able to get Uri of the selected photo and can display it. But how can I save the photo to my App to make sure it‘s always there even though it gets deleted from the gallery?
Ref: How to make a copy of a file in android?
To copy a file and save it to your destination path you can use the method below.
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
On API 19+ you can use Java Automatic Resource Management:
public static void copy(File src, File dst) throws IOException {
t
ry (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
I have tried to load cascade classifier in Android app, but the following condition always returns true and therefore the code can't be executed successfully:
cascadeClassifier.empty()
The code is the following:
try
{
InputStream is = getResources().openRawResource(R.raw.cascade);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "cascade.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
// Load the cascade classifier
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
if (cascadeClassifier.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
cascadeClassifier = null;
}
}
catch (Exception e)
{
Log.e("OpenCVActivity", "Error loading cascade", e);
}
The cascade.xml file is stored in raw folder and I have successfully tested it with python script - it successfully detects objects.
If this answer holds true, then I don't know what could be wrong in the code above as the trained cascade has been tested and the input stream is seems to be pointing to correct location (autocomplete lists R.raw.cascade).
I would be very thankful if anyone helped solve the issue.
The problem was solved by adding the following line after instantiating CascadeClassifier:
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
The working code is the following:
InputStream is = getResources().openRawResource(R.raw.object_detector);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "cascade.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytesRead);
Log.d(TAG, "buffer: " + buffer.toString());
}
is.close();
os.close();
// Load the cascade classifier
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
if (cascadeClassifier.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
cascadeClassifier = null;
}
I'm hitting an URL and saving the returned image response in cache dir. If I try to save Bitmap from Returned response inputstream then I get correct Bitmap. Now after saving that response inputstream in cache and after fetching it I'm getting null Bitmap
Write inputStream to cache dir -
String root = mContext.getCacheDir().toString();
String path = root + "/tomorrow.jpg";
try {
final File file = new File(path);
final OutputStream output = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) != -1)
output.write(buffer, 0, ch);
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
now I'm reading the file from cache dir -
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp1 = BitmapFactory.decodeStream(fin);
I'd like to thanks Dimitri Budiansky for guiding me. Fix as below-
//final byte[] buffer = new byte[1024];
//int ch;
//while ((ch = in.read(buffer)) != -1)
//output.write(buffer, 0, ch);
I commented above lines. Simply add below line.
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
for clarification u may check this Link
I am trying to share files between two Android phones using Socket programming. The problem is right now I have to hard code the file extension on the receiving end. Is there a way that I can automatically determine the extension of the file being received?
Here's my code.
Client Side
socket = new Socket(IP,4445);
File myFile = new File ("/mnt/sdcard/Pictures/A.jpg");
FileInputStream fis = null;
fis = new FileInputStream(myFile);
OutputStream os = null;
os = socket.getOutputStream();
int filesize = (int) myFile.length();
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
os.flush();
os.close();
fis.close();
socket.close();
}
And the Server side
FileOutputStream fos = null;
File root = Environment.getExternalStorageDirectory();
fos = new FileOutputStream(new File(root,"B.jpg")); //Here I have to hardcode B.jpg with jpg extension.
BufferedOutputStream bos = new BufferedOutputStream(fos);
ServerS = new ServerSocket(4445);
clientSocket = ServerS.accept();
InputStream is = null;
is = clientSocket.getInputStream();
int bytesRead = 0;
int current = 0;
byte [] mybytearray = new byte [329];
do {
bos.write(mybytearray,0,bytesRead);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
} while(bytesRead > -1);
bos.flush();
bos.close();
clientSocket.close();
}
You can find the file extension pretty easily by doing this:
String extension = filename.substring(filename.lastIndexOf('.'));