How to create File object from assets folder? - java

I am trying to read a pdf file from my assets folder but I do not know how to get the path of pdf file.
I right click on pdf file and select "copy Path" and paste it
Here is the another screen shot of my code:
Here is my code:
File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf");
if (file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show();
}
I always get file not found, Help me to create File object or let me know how I can get the exact path for a file I also tried with file:///android_asset/Introduction.pdf but no success. I also tried with Image.png but never gets file.exists() success. I am using Mac version of Android studio. Thanks

get input stream from asset and convert it to a file object.
File f = new File(getCacheDir()+"/Introduction.pdf");
if (!f.exists())
try {
InputStream is = getAssets().open("Introduction.pdf");
byte[] buffer = new byte[1024];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }

Short converter (storing asset as cache file) in Kotlin:
fun fileFromAsset(name: String) : File =
File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }
cacheDir is just shorthand for this.getCacheDir() and should be predefined for you.

Can you try this code
AssetManager am = getAssets();
InputStream inputStream = am.open("Indroduction.pdf");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("new FilePath");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Then try with
File file = new File("new file path");
if (file.exists())

Related

Can't create folder in internal storage

Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());

Save image to internal storage

I want to save some images in internal storage. Here is my code:
Bitmap bitmap = ((BitmapDrawable)iv_add.getDrawable()).getBitmap();
File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
file = new File(file, "UniqueFileName"+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
As I understood, the picture needs to go into internal_storage/android/data/project_name/file. When I choose a picture from my gallery and click the button to save it, nothing happens and the program starts lagging. What can I do?
This line is your problem.
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
You are not supposed to create the context wrapper yourself.
File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
file = new File(file, "UniqueFileName"+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}

Trying to read Text File from Uri Android

I created an android file chooser that returns the uri of a text file. I want to open and read the file and store it's data.My code is:
private void covertFile(Uri data) {
InputStream inputStream = getContentResolver().openInputStream(data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String myText = "";
int in;
try {
in = inputStream.read();
while (in != -1)
{
byteArrayOutputStream.write(in);
in = inputStream.read();
}
inputStream.close();
myText = byteArrayOutputStream.toString();
}catch (IOException e) {
e.printStackTrace();
}
myTextView.setText(myText);
}
But the line InputStream inputStream = getContentResolver().openInputStream(data); givesjava.Io.FileNotFoundException. How do I resolve this?
EDIT: Issue Resolved
First create file object
String path = data.toString();
File file = new File(path);
Now pass the file object as arg in InputStream
InputStream inputStream = getContentResolver().openInputStream(file);

Unable to get URI of a text file

I am trying to make an app in which I can take text input from the user store it in a text file and then upload that file to firebase so that I can retrieve it later.
The issue is that I am unable to get the correct URI of the file. Please help me get the URI.
Here is the code
public class TextUpload extends AppCompatActivity {
private void writeToFile(String data, Context context) throws FileNotFoundException {
mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!mediaFile.exists()) {
mediaFile.mkdir();
}
byte[] data2 = data.getBytes();
FileOutputStream f = new FileOutputStream(new File(mediaFile, "textfile.txt"));
try {
f.write(data2);
f.flush();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
fileUri = Uri.fromFile(mediaFile);
Log.d("TAHH" , "URI = "+fileUri);
}
}
This is the value I'm getting stored at fileUri
URI = file:///storage/emulated/0
[
Please help me get the URI of the highlighted file.
Main problem is that you are reading the path of mediaFile which is a directory (not the file itself). mediaFile is the parent directory of the file that you want.
So, change to this:
mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!mediaFile.exists()) {
mediaFile.mkdir();
}
byte[] data2 = data.getBytes();
// Hold the reference to the file that you are writting
File txtFile = new File(mediaFile, "textfile.txt")
FileOutputStream f = new FileOutputStream(txtFile );
try {
f.write(data2);
f.flush();
f.close();
} catch (IOException e) {
e.printStackTrace();
}
// Here, use txtFile instead of mediaFile
fileUri = Uri.fromFile(txtFile);
Log.d("TAHH" , "URI = "+fileUri);

EROS | Read Only file system error

In my android app, i am logging errors in a txt file. But when i try to create file , i face an error Java.io.IOException: open failed: EROS( Read Only file system error). I have added write permissions in AndroidManifest.xml but no difference. How to fix it ?
code
try {
File file =new File("Log.txt");
if(!file.exists()){
file.createNewFile();
}
catch (Exception e)
{
Log.w("tun tun", e.toString());
}
Do this way
To store on external storage(SDCARD)
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Log.txt");
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
Log.w("tun tun", e.toString());
}
To store In internal storage
try {
File file = new File(context.getCacheDir() + File.separator + "Log.txt");
if (!file.exists()) {
file.createNewFile();
}
} catch (Exception e) {
Log.w("tun tun", e.toString());
}
try some below codes:-
Problem is you are not adding path.
String filePath = context.getFilesDir().getPath().toString() + "/fileName.txt";
File f = new File(filePath);
or
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
refrence
or
path = Environment.getExternalStorageDirectory();
File file = new File(path, "/" + fname);
Data directory has no read/write permission in Android

Categories