I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException
Related
I have created a file and I want to write in bytes in this file but it's not working. Where is the problem?
public void writeFileExternalStorage() {
File file = new File(getExternalFilesDir(null), "hhh.txt");
try {
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream ;
outputStream = new FileOutputStream(file, true);
outputStream.write(files.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The createNewFile call will return true if it has successfully created the file. You should check the result of the call, and log an error if it is false.
According to the documentation for getExternalFilesDir (javadoc):
[it m]ay return null if shared storage is not currently available.
If that happens you will call new File(null, "hhh.txt"). That is equivalent to new File("hhh.txt") (javadoc), so the file would be created in the app's "current user directory".
I'm making an Android application that captures images and stores them in the internal memory, but to save the images are compressed and I want to be saved in its original size without any compression.
This is the code I am using to store images, as I do so not me compress ??
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, "TheChat" + (System.currentTimeMillis()/1000) + "Avatar.jpg");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Save it as a BLOB (bytearray), then reconvert it to a bitmap upon loading it. If it's for internal use only it should work fine. If you're not compressing it at all you might as well save it in a straight-forward format.
I'm using java SE eclipse.
As I know, When there are no file named by parameter FileOutputStream constructor create new file named by parameter. However, with proceeding I see that FileOutputStream make exception FileNotFoundException. I really don't know Why this exception needed. Anything wrong with my knowledge?
My code is following(make WorkBook and write into file. In this code, although there are no file "data.xlsx", FileOutpuStream make file "data.xlsx".
public ExcelData() {
try {
fileIn = new FileInputStream("data.xlsx");
try {
wb = WorkbookFactory.create(fileIn);
sheet1 = wb.getSheet(Constant.SHEET1_NAME);
sheet2 = wb.getSheet(Constant.SHEET2_NAME);
} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
e.printStackTrace();
} // if there is file, copy data into workbook
} catch (FileNotFoundException e1) {
initWb();
try {
fileOut = new FileOutputStream("data.xlsx");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // if there is not file, create init workbook
} // ExcelData()
If anything weird, please let me know, thank you
It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't)
File yourFile = new File("score.txt");
yourFile.createNewFile();
FileOutputStream oFile = new FileOutputStream(yourFile, false);
Answer from here: Java FileOutputStream Create File if not exists
There is another case, where new FileOutputStream("...") throws a FileNotFoundException, i.e. on Windows, when the file is existing, but file attribute hidden is set.
Here, there is no way out, but resetting the hidden attribute before opening the file stream, like
Files.setAttribute(yourFile.toPath(), "dos:hidden", false);
This is the code I have in my onCreate() method in the starting activity for my app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
Bitmap bm = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.img);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//write the bytes in file
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
It is meant to load an image into a bitmap and then make a file on the SD card named "test.jpg" with the image inside, however this is not what is happening.
Instead, I get a null pointer exception on the line
fo.write(bytes.toByteArray());
The error message is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.daniel.firstapp/com.example.daniel.firstapp.startup}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.FileOutputStream.write(byte[])' on a null object reference
First: Why so many try/catch?
Second: Your fo variable is null.
Probably because the file could not be created.
Make sure you have this in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can drop the ByteArrayOutputStream and replace it with a FileOutputStream instead.
NB: try/catch blocks omitted for clarity.
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
// 'this' in the following line refers to an instance of your Activity, if you're doing your output from a fragment or helper class, get a reference to your activity.
FileOutputStream fos = this.openFileOutput(f.getName(), Context.MODE_PRIVATE);
Bitmap bm = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.img);
//PNG doesn't compress because it's lossless
bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bm.recycle();
also make sure you have the appropriate write external storage permission set in your manifest.
starting from android 4.4, normal applications are not allowed to access secondary external storage devices, i.e. sd card, except in their package-specific directories, even if you have requested WRITE_EXTERNAL_STORAGE permission.
The WRITE_EXTERNAL_STORAGE permission must only grant write access to
the primary external storage on a device. Apps must not be allowed to
write to secondary external storage devices, except in their
package-specific directories as allowed by synthesized permissions.
Restricting writes in this way ensures the system can clean up files
when applications are uninstalled.
https://source.android.com/devices/storage/
Actually your application has thrown exception in the line below, because of the restriction.
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
First of all, I'm sorry if exists a similar post but I was not able to understand.
I'm trying to write a file in android and I got the following code:
String FILENAME = "hello_file.txt";
String string = "hello world!";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Angles", "FileNotFoundException");
}catch(IOException e){
e.printStackTrace();
Log.d("Angles", "IOException");
}
I don't get any exception so I suppose it works but I'm not able to find the hello_file.txt file inside the device.
I'm running on Galaxy Nexus; no sd.
If you want to create a file in sdcard, you need to use
File f = new File (Environment.getExternalStorageDirectory(),"myfile.txt")