On Aug 30, 4:36 pm, Kristoz <[EMAIL PROTECTED]> wrote:
> The given source file does not include any try catch for the file
> operations.
> Should the input file data be something like:
>
> // set up new properties object
> // from file "myProperties.txt"
> String fileName = "myProperties.txt";
> // retrieve system properties
> Properties p = new Properties(System.getProperties());
> // attempt to load file contents
> try {
> FileInputStream propFile = new
> FileInputStream(fileName);
> p.load(propFile);
> } catch (FileNotFoundException fnfe) {
> System.out.println(fileName + " not found");
> } catch (IOException ioe) {
> System.out.println("error accessing " + fileName);
> }
Even if there is a throws Exception in the main method, it is better
to actually catch the exceptions.
In this case, your proposal is almost OK, as you should close the
input stream in a finally clause in case it has been opened, and
nevertheless also have a throws IOException clause precisely for the
close statement. So, that gives the following program:
Note, I've used logs here, but you may use a mere printing. Note also
the refactoring, propFile should be initialized to null before the
try, so that it exists in all cases, and this is the wole block which
uses propFile which should be in the try block to ensure any failure
will not be propagated elsewhere.
package systempropertiesproject;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author miga
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// set up new properties object
// from file "myProperties.txt"
FileInputStream propFile = null;
Properties p = new Properties(System.getProperties());
try {
propFile = new FileInputStream("myProperties.txt");
p.load(propFile);
// set a property through setProperty() method
p.setProperty("myKey1", "myValue1");
// set the system properties
System.setProperties(p);
// display new properties
System.getProperties().list(System.out);
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (propFile != null) {
propFile.close();
}
}
}
}
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---