I have sourcehandler.java class which has the code
public class SourceHandler {
String PrpPath = null;
Properties prop = null;
public Properties loadConfigProperties() {
try {
System.out.println("Propertiess " +PrpPath );
InputStream in =new FileInputStream(new File(PrpPath ));
prop.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
and main method in a different class,
public static void main(String[] args) throws ParserConfigurationException,
Exception {
try {
SourceHandler conf = new SourceHandler();
conf.setProperties("C:/config.properties");
Properties p = conf.loadConfigProperties();
System.out.println("Done");
} catch (DOMException dome) {
// TODO: Add catch code
dome.printStackTrace();
}
Now, if i run the code , it shows null pointer exception at line , prop.load(in);
stack trace:
java.lang.NullPointerException
at DecryptEncryptSource.SourceHandler.loadConfigProperties(SourceHandler.java:98)
at DecryptEncryptSource.SourceHandler.updateCofigDestn(SourceHandler.java:151)
at DecryptEncryptSource.MainClass.main(MainClass.java:27)
First of all,
InputStream in =new FileInputStream(new File(Properties));
should better read
InputStream in =new FileInputStream(new File(propertyFileName));
to avoid any ambiguity; and then:
Are you sure that there is really a file named C:\config.properties
Probably you need either escaping: C:\\config.properties; or you try C:/config.properties
Regarding the update; you have this line:
Properties prop = null;
and further down:
prop.load(in);
And you are surprised that you get a NPE? Really? Hint: look into your code and create that Property object using the file path; instead of just calling a method on a null object.
And the real answer is read this here over and over again.
(and for those who wonder why I didn't close out as duplicate ... I can't any more, because I already close-requested on another reason )
Related
public void readList () {
try {
FileOutputStream writeData = new FileOutputStream("Accounts.txt");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(AccountCredentials);
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void writeList() {
try {
FileInputStream readData = new FileInputStream("Accounts.txt");
ObjectInputStream readStream = new ObjectInputStream(readData);
AccountCredentials = (ArrayList <Accounts>) readStream.readObject();
readStream.close();
System.out.println(AccountCredentials.size());
}
catch (Exception e) {
e.printStackTrace();
}
}
My readList method works fine right, I have ¬í sr java.util.ArrayListxÒ™Ça I sizexp w
in the file. My writeList does not. I have a School folder inside the Netbeans folder, and in the main directory is Accounts.txt. Do I need to specify that? My Java file is in Schools/src. It always says my list size is 0
Can you please share the exception or stack trace you are getting and paste it here ? , Also I would highly recommend not to use a flat file for storing the account credentials, rather use any of the identity management solution and db driven account management. Did you also try to debug the following line "ObjectInputStream readStream = new ObjectInputStream(readData);"
I'm trying to create a new PrintWriter object within a try with resources block as below, but it's giving me an error saying outFile cannot be resolved to a type:
public class DataSummary {
PrintWriter outFile;
public DataSummary(String filePath) {
// Create new file to print report
try (outFile = new PrintWriter(filePath)) {
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
EDIT:
A reason why I didn't want to declare the PrintWriter object within the try block is because I want to be able to reference the outFile object in other methods of my class.
It seems like I can't do it with try with resources, so I created it within a normal try/catch/finally block.
The text file is being created. However, when I try to write to file in another method, nothing seems to be printing in the text file, test.txt.
Why is this??
public class TestWrite {
PrintWriter outFile;
public TestWrite(String filePath) {
// Create new file to print report
try {
outFile = new PrintWriter(filePath);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} finally {
outFile.close();
}
}
public void generateReport() {
outFile.print("Hello world");
outFile.close();
}
}
Instead of trying to do everything in a constructor, I will demonstrate the preferred way to use a try-with-resources and invoke another method. Namely, pass the closeable resource to the other method. But I strongly recommend you make the opener of such resources responsible for closing them. Like,
public void writeToFile(String filePath) {
try (PrintWriter outFile = new PrintWriter(filePath)) {
generateReport(outFile);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
}
private void generateReport(PrintWriter outFile) {
outFile.print("Hello world");
}
Would this be problematic and run into issues?
Example:
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
try {
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (FileNotFoundException ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
}
If it is problematic, what other approach should I look to?
Too many try-catch would complicate code and reduce the code readability which will lead to swallowing an exception and its much more worse than performance issues as it can crash your system unexpectedly.
Here is an example of swallowing an exception and its side effects (multiple point of failures like NPE etc.).
public static void main(String[] args) {
String dataFromFile = null, dataFromDataBase = null;
try {
try {
dataFromFile = readFile();
} catch (IOException e) {
// ignore exception
// String dataFromFile will be set to null
// as there was an exception
}
// imagine many lines of code here
dataFromDataBase = readDatabase(dataFromFile.getKey());
} catch (IOException e) {
// ignore exception
}
// imagine many lines of code here
System.out.println(dataFromFile.replace(" ", ""));
//imagine many lines of code here
System.out.println(dataFromDataBase.getKey());
}
private static String readFile() throws IOException {
// throws ioexception
}
private static String readDatabase(String key) throws IOException {
// throws ioexception
}
If you are expecting multiple points in a single method that can throw exceptions then club them into one try-catch and handle them appropriately. Again there can be exception to this specific question but you should always try to reduce multiple try-catch in single method.
Unless you are doing something specific with an exception, use single Exception clause to handle all exception and log details or throw it to the caller to handle it in its own specific ways.
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// while-statement -- extract information from blah
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
// while-statement -- extract information from blah2
} catch (Exception ex) {
// Display Exception stuff details
}
}
In this example I see no reason to start a new try statement. why not do this?
try {
File Reader fileReader = new FileReader(blah);
BufferedReader bufferedReader = new BufferedReader(fileReader);
File Reader fileReader2 = new FileReader(blah2);
BufferedReader bufferedReader2 = new BufferedReader(fileReader2);
} catch (FileNotFoundExcpetion ex) {
// Display FileNotFound stuff
} catch (IOException ex) {
// Display IOException stuff
}
But no, there would be no problem. it just looks bad. but sometimes needed I guess.
public class deleteFile {
public static void main(String args[]){
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append("c:/");
fileNameStr.append("Test");
File file = new File(fileNameStr.toString());
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
}
According to this code, when I get SQLException, it can't delete file. Why?
There is nothing special about deleting a file in a catch block.
If your code (above) is not deleting the file, then it could be a number of things:
You may have the file pathname incorrect.
The file may not exist in the first place.
Your application may not have permission to delete the file, due to normal file / directory permission issues, "mandatory access control" restrictions (e.g. SELinux) or Java sandbox restrictions.
The file may be undeletable because it is "in use" ... on Windows.
That particular exception may not be being thrown.
Your catch block with SqlException never catching.
Use finally{} block in order to delete file or free resource.
Actually my full source code is,
public class deleteFile {
public static void main(String args[]){
-------------------------
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append(.....);
fileNameStr.append(.....);
File file = new File(fileNameStr.toString());
PrintWriter printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),
"windows-31j")));
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
Finally I found the solution that is need to close printWriter before deletion file. Thank you for your advice.
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
printWriter.flush();
printWriter.close();
file.delete();}
}
I'm having the following problem. I'm using Java properties to read some info of a file, but when I call prop.getProperty("var") it returns null. I ran out of ideas. Here is the code I have.
static final Properties prop = new Properties();
public JConnection(){
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
I never get the error message "file not found".
public static Connection getConnection(String conType) {
Connection conn;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
if(model == "client"){
conn = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("usr"),prop.getProperty("pass"));
}else{
conn = DriverManager.getConnection(prop.getProperty("url1"),prop.getProperty("usr1"),prop.getProperty("pass1"));
}
} catch (Exception ex) {
ex.printStackTrace();
conn = null;
}
When it tries to connect to the DB, getProperty is returning null as it is not found. Any ideas of what it could be or what I'm doing wrong?
Another wild guess: I noticed that both your prop variable and the method that's reading from it are static, so maybe you are using this as some sort of static utilities class without ever creating an instance of the class? In this case, you are never calling the constructor and never actually loading the properties file. Instead, you might try this:
static final Properties prop = new Properties();
static {
try{
prop.load(new FileInputStream("db.properties"));
}catch(Exception e){
logger.info("file not found.");
e.printStackTrace();
}
}
You have a static field (prop), but you initialize it in a constructor. This means if you consult your prop object before you construct any object of JConnection, prop will not be initialized.
You can try something like this:
public class JConecction {
static final Properties prop = new Properties();
static {
try {
prop.load(new FileInputStream("db.properties"));
} catch(Exception e) {
logger.info("file not found.");
e.printStackTrace();
}
}
}