I have this code:
private void save(Bitmap bitmap) {
try {
FileOutputStream fos = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Do I need to close the FileOutputStream in FileNotFoundException catch block?
If that exception is thrown means that file could not be opened so I think that it would not be necessary. However, I think it would be nice to do it in IOException catch block.
Could it cause any memory leak error or something similar if I don't do it?
Thanks.
If you are working in Java 7 or above you should use a try with resources and let the system decide.
private void save(Bitmap bitmap) {
try (FileOutputStream fos = new FileOutputStream(path)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If not then just ensure that the stream is not null first and do it in a finally.
private void save(Bitmap bitmap) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}
There is nothing to close. The FileOutputStream constructor threw an exception; the stream was never constructed; the fos variable has never been assigned; and it is out of scope in the catch block.
You should always close the file once you have finished to read or write. Otherwise you will keep the resource busy and in general could be a problem.
If you modify your code in this way you will not have to care about close the file and java will think about it.
private void save(Bitmap bitmap) {
try(FileOutputStream fos = new FileOutputStream(path)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I need to pass some Bitmaps from one activity to another, and, since the size limit of the Bundle won't let me pass these images (even using a byte array*), I thought that I could use a getter method between these Activities.
-But, since I'm still not a master in Android (Java), I don't know if that would make any difference, and, if it does, what should I watch out for when using it.
the byte array did reduce the total size(at about 60%), but it still wasn't enough
scaling down is a way out, but just in case any other solution works
save your object in a file
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve the object from another activity
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pass through Uri by writing getter method in POJO class
If you want to use getter setter, just create URI of your bitmap and pass to setter method in POJO class and then retrieve using getter method of POJO class.
in one of the activities when a button is pressed i want to create a file on the extran storage. so i wrote
the below code to do so.
but in the end the file is created but empty..why?
code:
public void tx(byte[] data) {
Log.w(TAG, CSubTag.bullet("tx"));
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream os = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(os);
try {
bos.write("data_stream".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Please close the OutputStream and BufferedOutputStream inside finally block. Otherwise, the data will not be written.
I'm having problems with appending a generic object within an existing file. This method is supposed to append the object to the existing file if the parameters are "true" and overwrites the entire file if "false". The "false" statement works perfectly fine, it overwrites the entire file but I can't seem to get the append one to work. It seems to do nothing at first glance but when I placed a simple System.out.println("test"); in the while (true) loop, it runs forever. How can I fix this?
public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{
if (append == true){
//TODO
if (file.exists ()){
ObjectOutputStream ois = null;
try{
ois = new ObjectOutputStream (new FileOutputStream (file, true));
while (true){
ois.writeObject(type);
}
}catch (StreamCorruptedException e){
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (StreamCorruptedException e){
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
else { //overwrites the entire file
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(type);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (StreamCorruptedException e) {
System.out.println("error");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I also have this inside the class:
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}
I am using the following method to read from the internal storage:
private void deserialize(ArrayList<Alias>arrayList) {
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<Alias>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
It reads the content of the file "filename" to the "arrayList".
The "serialize" method is as follows:
void serialize(ArrayList<Alias>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that I whenever I run my program again, the "arrayList" is empty. So I guess I am opening the file in wrong input mode.
My aim is to first get the array from the file, then modify it within the app, and then write the modified array back to the file.
Can someone please help me with my problem?
Thanks!
Can you post your pice of your source code? I think the way which you used to parse file content get issue.
Read here:
Android ObjectInputStream docs
I read that the method readObject() read the next object...i this that you must iterate with something like this:
MediaLibrary obj = null;
while ((obj = (MediaLibrary)objIn.readObject()) != null) {
libraryFromDisk.add(obj);
}
I have following code :
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
}catch (IOException e) {
system.out.println("IOEXCeption");
}
Is it required to close the FileInputStream? If yes, how do I do that? I am getting a bad practice error in my code checklist . Asking it to put finally block.
You must the close the FileInputStream, as the Properties instance will not. From the Properties.load() javadoc:
The specified stream remains open after this method returns.
Store the FileInputStream in a separate variable, declared outside of the try and add a finally block that closes the FileInputStream if it was opened:
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream("filename.properties");
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
} finally {
if (null != fis)
{
try
{
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use try-with-resources since Java 7:
final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOEXCeption: " + e.getMessage());
}
You should always close your streams, and doing it in the finally block is a good practice. The reason for this is that the finally block always gets executed, and you want to make sure that the stream is always closed, even if Something Bad happens.
FileInputStream inStream = null;
try {
inStream = new FileInputStream("filename.properties");
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
} finally {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are using Java 7, this becomes much easier, since a new try-with syntax was introduced. Then you can write like this:
try(FileInputStream inStream = new FileInputStream("filename.properties")){
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
}
and the stream is closed automatically.
here is an example:
public class PropertiesHelper {
public static Properties loadFromFile(String file) throws IOException {
Properties properties = new Properties();
FileInputStream stream = new FileInputStream(file);
try {
properties.load(stream);
} finally {
stream.close();
}
return properties;
}
}
You can use Lombok #Cleanup to do it simply.
http://projectlombok.org/features/Cleanup.html
Properties properties = new Properties();
try {
#Cleanup FileInputStream myFis = new FileInputStream("filename.properties");
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}
Or, only if your are using Java 7, there is the "try with resource" new feature.
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Properties properties = new Properties();
try (FileInputStream myFis = new FileInputStream("filename.properties")) {
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}