Create FileUtil fuction in android
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.OpenableColumns; import android.util.Log;
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;
public class FileUtil { private static final int EOF = -1; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private FileUtil() {
}
public static File from(Context context, Uri uri) throws IOException { InputStream inputStream = context.getContentResolver().openInputStream(uri); String fileName = getFileName(context, uri); String[] splitName = splitFileName(fileName); File tempFile = File.createTempFile(splitName[0], splitName[1]); tempFile = rename(tempFile, fileName); tempFile.deleteOnExit(); FileOutputStream out = null; try { out = new FileOutputStream(tempFile); } catch (FileNotFoundException e) { e.printStackTrace(); } if (inputStream != null) { copy(inputStream, out); inputStream.close(); }
if (out != null) { out.close(); } return tempFile; }
private static String[] splitFileName(String fileName) { String name = fileName; String extension = ""; int i = fileName.lastIndexOf("."); if (i != -1) { name = fileName.substring(0, i); extension = fileName.substring(i); }
return new String[]{name, extension}; }
@SuppressLint("Range") private static String getFileName(Context context, Uri uri) { String result = null; if (uri.getScheme().equals("content")) { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } if (result == null) { result = uri.getPath(); int cut = result.lastIndexOf(File.separator); if (cut != -1) { result = result.substring(cut + 1); } } return result; }
private static File rename(File file, String newName) { File newFile = new File(file.getParent(), newName); if (!newFile.equals(file)) { if (newFile.exists() && newFile.delete()) { Log.d("FileUtil", "Delete old " + newName + " file"); } if (file.renameTo(newFile)) { Log.d("FileUtil", "Rename file to " + newName); } } return newFile; }
private static long copy(InputStream input, OutputStream output) throws IOException { long count = 0; int n; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } } |
The code you provided looks good and should work for reading the content of a file into a byte array. It retrieves the URI of an image, converts it to a File object using FileUtil.from(), then reads the content of the file into a byte array.
However, there are a couple of things to consider:
Permissions: Make sure you have the necessary permissions to access the image URI. If you're dealing with images from external storage or other apps, you might need to request appropriate permissions.
Exception Handling: In your code, you're catching IOException to handle exceptions that might occur during file reading. This is a good practice. Just make sure that any exceptions are handled appropriately in your app's logic. You're currently displaying the exception message as a toast, which can be useful for debugging purposes during development.
UI Thread: Keep in mind that certain operations, like showing a Toast, should be done on the UI thread. It seems you're already doing this correctly.
File Size: The code calculates the length of the file and creates a byte array of the same length. This can be problematic if the file is too large, as it might lead to memory issues. Consider using a buffer and reading the file in chunks if you're dealing with potentially large files.
Overall, the code you provided should work for reading the file's content into a byte array, as long as you handle permissions and any potential exceptions that might occur during file access.
app/src/main/java/com/example/app/Api.java
@Override
public void onActivityResult(int requestCode,
int resultCode,
@Nullable Intent data) {
try {
Uri imgeUri=data.getData();
File file = FileUtil.from(getContext(), imgeUri);
// Open an input stream for the file
FileInputStream inputStream = new FileInputStream(file);
// Calculate the length of the file
int fileLength = (int) new File(file.getPath()).length();
// Create a byte array to store the file content
byte[] fileBytes = new byte[fileLength];
// Read the file content into the byte array
inputStream.read(fileBytes);
// Close the input stream
inputStream.close();
Toast.makeText(getContext(), ""+fileBytes.length, Toast.LENGTH_SHORT).show();
// Now you have the file content as a byte array (fileBytes)
} catch (IOException e) {
// Handle any exceptions that might occur during file reading
e.printStackTrace();
Toast.makeText(getContext(), ""+e, Toast.LENGTH_SHORT).show();
}}