Created
January 10, 2020 03:55
-
-
Save ltvu93/d19e7737191de12adcc5679d475b07b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ApplicationScope | |
public class FileHelper { | |
private Context context; | |
@Inject | |
public FileHelper(Context context) { | |
this.context = context; | |
} | |
@Nullable | |
public AppFile getAppFile(@NonNull Uri uri) { | |
Cursor cursor = | |
context.getContentResolver().query(uri, null, null, null, null); | |
if (cursor != null) { | |
cursor.moveToFirst(); | |
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); | |
String fileName = cursor.getString(nameIndex); | |
cursor.close(); | |
return new AppFile(fileName, uri); | |
} else { | |
return null; | |
} | |
} | |
public byte[] getBytes(@NonNull Uri uri) throws IOException { | |
InputStream inputStream = context.getContentResolver().openInputStream(uri); | |
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); | |
int bufferSize = 1024; | |
byte[] buffer = new byte[bufferSize]; | |
int len; | |
while ((len = inputStream.read(buffer)) != -1) { | |
byteBuffer.write(buffer, 0, len); | |
} | |
return byteBuffer.toByteArray(); | |
} | |
} | |
public class AppFile { | |
private String name; | |
private Uri uri; | |
public AppFile(String name, Uri uri) { | |
this.name = name; | |
this.uri = uri; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public Uri getUri() { | |
return uri; | |
} | |
public void setUri(Uri uri) { | |
this.uri = uri; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment