how to close the fileInputStream while reading the property file - java

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");
}

Related

Get data from getter method instead of passing in a Bundle

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.

output stream doesn't make a file

The code below is supposed to create and write to a file, but it doesn't create a file in my directory. Everything with the Scanner is working, it scans everything from jTextField perfectly.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}
Can someone please help me find the problem?
Don't use a nested try, it doesnt have any sense and could case a lot of problems in terms of exception handling.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
}
catch (FileNotFoundException e) {
}
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}

Should I close output stream if I get FileNotFoundException? And IOException?

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();
}
}

How to close a RandomAccessFile

I'm trying to close a RandomAccessFile but resource remain busy.
Code:
public boolean isOpen(RandomAccessFile f) {
try {
f.length() ;
return true ;
}
catch (IOException e) {
return false ;
}
}
this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");
Log is not showed and thread goes in loop.
When I try to access to my resource from shell it gives me "Device or Resource busy".
The only way to access is kill java process.
When you are trying to access the RandomAccessFile length(), method, it is already closed and thus you cannot access it anymore.
You probably want to use the length() method of File. Your loop cannot work as the RandomAccessFile was already closed.
But I must admit I am clueless on the low level reason why rfmRandomAccessFile would not really be closed. It could be a side effect of your strange loop trying to get the size of a closed file.
[edit:]Could not reproduce your issue with the following piece of code:
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("foobar.txt");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rws");
randomAccessFile.write(new byte[]{'f'});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(randomAccessFile !=null){
try {
randomAccessFile.close();
} catch (IOException e) {
//doh!
}
}
}
FileReader reader = null;
try {
reader = new FileReader(file);
char read = (char) reader.read();
System.out.println("what was written: "+read);
System.out.println("file size: "+file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){
try {
reader.close();
} catch (IOException e) {
//doh!
}
}
}
}
}

How to append an object to an existing file (generics)?

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() {}
}

Categories