I am using PDF Viewer Library to view PDF inside an Android app. I've browsed through a lot of tutorials, one of which is Dipak's tutorial. I want to access a PDF file stored in my assets folder instead of accessing the external storage. My problem is, I can't get the "path" right. It always return file not found.
I've tried the following, still yields the same result:
this.getAssets()
file:///android_assets/file_name.pdf
file:///android_asset/file_name.pdf
You can't get path from asset, have to right in sd or internal memory to get the path.
For SD Card
First Take Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
then write it in card
File f = new File(Environment.getExternalStorageDirectory() + "file.pdf");
if (!f.exists()) try {
InputStream is = getAssets().open("file.pdf");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
Staring path = f.getPath();
Related
I followed the answers of Saving an image from ImageView into internal storage but I still can't save anything.. My code is here :
public void buttonPickImage(View view) {
FileOutputStream fos;
bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Random rng = new Random();
int n = rng.nextInt(1000);
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/BAC");
bool = dir.mkdir();
File file = new File(dir, "BAC_"+n+".jpg");
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(),"Image sauvegardée"+bool,Toast.LENGTH_SHORT).show();
}catch (java.io.IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"IOException: " + e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
With this method I get the IOExeception with messae : java.io.FileNotFoundException: /storage/emulated/0/BAC/BAC_396.jpg: open failed: ENOENT (No such file or directory)
I also tried this to save it to internal storage but its not working for me :
https://www.tutorialspoint.com/how-to-write-an-image-file-in-internal-storage-in-android
With this method, program runs but boolean mkdir gives me false.
Thanks for helping me
Finally got it working using Media Store instead of getExternalStorageDirectory as
This method was deprecated in API level 29.
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.
MediaStore is also useful as it allows you to get the image in your android gallery app.
So my solution is :
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "any_picture_name");
values.put(MediaStore.Images.Media.BUCKET_ID, "test");
values.put(MediaStore.Images.Media.DESCRIPTION, "test Image taken");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outstream);
outstream.close();
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
Still thank you #blackapps for explaining me some basics things about the IOexception, mkdir and toasts. It'll be useful anyway.
I would like to delete an internal file at runtime. When I download from an external server, the old version of the file (with the same name) is replaced, however I am unable to read it. I think that I need to delete the previous file before downloading the new version. Here is an example of what I have tried so far:
try {
FileOutputStream fos = getApplicationContext().openFileOutput("mytext.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(pictosFile.getAbsolutePath()).getBytes());
Log.e("mytextfile",""+getStringFromFile(pictosFile.getAbsolutePath()));
progressDialog.cancel();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
This allows me to save the file into internal memory, but I am unsure about how to delete the previous file before writing the new version.
If you need to ensure that the file is overwritten, i.e. delete an old copy before saving a new version, you can use the exists() method for a file object. Here is an example showing how to delete an old version of an image file before writing a new file with the same name in a nested directory:
// Here TARGET_BASE_PATH is the path to the base folder
// where the file is to be stored
// 1 - Check that the file exists and delete if it does
File myDir = new File(TARGET_BASE_PATH);
// Create the nested directory structure if it does not exist (first write)
if(!myDir.exists())
myDir.mkdirs();
String fname = "my_new_image.jpg";
File file = new File(myDir,fname);
// Delete the previous versions of the file if it exists
if(file.exists())
file.delete();
String filename = file.toString();
BufferedOutputStream bos = null;
// 2 - Write the new version of the file to the same location
try{
bos = new BufferedOutputStream(new FileOutputStream(filename));
Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.PNG,90,bos);
bmp.recycle();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
try{
if(bos != null)
bos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
You must also ensure that you have read / write access to memory, make sure that you ask the user for these permissions at run time and have the following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
saving socres to highscore.sav file, it works fine on desktop, but not on android. why?
String fileName = "highScores.sav";
file = new File(fileName);
public static void save(){
try{
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(gd);
out.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
public static void load(){
try{
if(!saveFileExists()){
init();
return;
}
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
gd = (GameData) in.readObject();
in.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
got error: java.io.FileNotFoundException: /highScores.sav: open failed: EROFS (Read-only file system)
This isn't working because you have not specified a directory to save into. Android has tight restrictions on where an app can write files.
You don't need any permissions to read or write a file to internal memory. But you do need to specify internal memory (called local memory in libgdx).
Libgdx already handles this directly for you so you don't need to differentiate between desktop and Android. This explains exactly how to do it. All you need is the string or bytes you want to write into the file, and the libgdx API's handle the rest.
FileHandle file = Gdx.files.local(filename);
file.writeString(stringToWrite, false);
If you want to continue using your method of writing the file, you can get the path to the file like this:
String fileName = "highScores.sav";
file = new File(Gdx.files.getLocalStoragePath () + "/" + fileName);
Have you added the permission to the android app to allow writing to the storage space?
Hi I am developing app which downloads the images from the web site
and then i am displaying them as slide show. Now I want save the
downloaded images into my SD card please help me.
My current attempt is:
File imageFileFolder = new File(Environment
.getExternalStorageDirectory(), "test");
imageFileFolder.mkdir();
File imageFileName = new File(imageFileFolder, date
+ pBean.getAuthorName());
InputStream fis = pBean.getInputStream();
byte[] data = new byte[fis.available()];
fis.read(data);
FileOutputStream fos = new FileOutputStream(imageFileName);
fos.write(data);
fos.close();
fis.close();
There are lot of examples available for this
Check this post
Lazy load of images in ListView
and link
http://open-pim.com/tmp/LazyList.zip
In your AndroidManifest.xml you'll need to add the permission to write
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Then just get get the path to your filename and make sure your directories exist before trying to write the file to the sdcard.
String imageFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/somedirectory/imagename.jpg"
I have downloaded a file from HttpConnection using the FileOutputStream in android and now its being written in phone's internal memory on path as i found it in File Explorer
/data/data/com.example.packagename/files/123.ics
Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.
Any suggestions?
This is what I am doing:
try
{
FileInputStream fileIn;
fileIn = openFileInput("123.ics");
InputStream in = null;
EditText Userid = (EditText) findViewById(R.id.user_id);
byte[] buffer = new byte[1024];
int len = 0;
while ( (len = in.read(buffer)) > 0 )
{
Userid.setText(fileIn.read(buffer, 0, len));
}
fileIn.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);
Similar post here
read file from phone memory
If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics"); will return you a FileInputStream on the file in question.
Or, call getFilesDir() to get a File object pointing to /data/data/com.example.packagename/files, and work from there.
I am using this code to open file in internal storage. i think i could help.
File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");