java - reading .properties file and storing it in properties object - java

As mentioned in the title I have to read a .properties file in java and store it in a Properties object. I use a jFileChooser from java swing to get the file, which actually works, then I pass the file to a new window as calling arguments and then I use the load() method to store it in a Properties object but I get the java.lang.NullPointerException error. I hope I was clear as trying to explain it.
This is the code:
public void actionPerformed(ActionEvent e3) { //when button is pressed
JFileChooser fc2 = new JFileChooser (new File("C:\\Users\\Ciurga\\workspace\\PropertiesManager"));
fc2.setDialogTitle("Load Default Values File");
fc2.setFileFilter(new FileTypeFilter(".properties", "Properties File"));
int result = fc2.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
df = fc2.getSelectedFile(); //getting selected file and storing it in "df" which will be passed as calling argument
defaultNameTextField.setText(df.getName());
}
}
This is how I pass the file to the other window:
public void actionPerformed(ActionEvent e1) {
FormWindow w1 = new FormWindow (df, lf); //when button is pressed, create new window passing the files i got with jFileChooser
}
And this is how I tried to store it in a Properties object:
private static Properties propDef;
private static Properties propLim;
private void run(File def, File lim) {
try {
propDef.load(new FileInputStream(def));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
propLim.load(new FileInputStream(lim));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(propDef.getProperty("name"));
}
Thank you guys, as you said I only had to initialize it and now it seems to work correctly, it was a simple error but I'm actually a beginner in java.
This is what I changed:
private static Properties propDef = new Properties();
private static Properties propLim = new Properties();

You never initialised propDef, thats why you get the NullPointerException.
If you did initialise it, please provide the code!

Probably, your propDef and propLim are null and when you call propDef.load(new FileInputStream(def)); you get a NPE because load method is instance method.

Related

Android: File not found exception, it worked in the first time?

I am performing a project, where so far in the discipline, we can not use database to persist the data. I am persisting the data in .tmp files. The first time I persisted the list of doctors, and it worked, but now that I'm trying to persist the patient user data, but this error happens, that file is not found.
These are my load, anda save methods in the class "SharedResources":
public void loadUserPatient(Context context) {
FileInputStream fis1;
try {
fis1 = context.openFileInput("patient.tmp");
ObjectInputStream ois = new
ObjectInputStream(fis1);
userPatient = (UserPatient) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
public void saveUserPatient(Context context) {
FileOutputStream fos1;
try {
fos1 = context.openFileOutput("patient.tmp",
Context.MODE_PRIVATE);
ObjectOutputStream oos =
new ObjectOutputStream(fos1);
oos.writeObject(userPatient);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
here is the whole class: https://ideone.com/f3c74u
the error is happening on line 16 of MainActivity:
SharedResources.getInstance().loadUserPatient(this);
here is the whole class "Main": https://ideone.com/OyiljP
And I think this error is ocurring because of the 52nd line of the UserPatientAdd class:
SharedResources.getInstance().getUserPatient();
because when I work with an ArrayList, I put an add at the end of the line, like:SharedResources.getInstance().getDoctors().add(doctor);
And I get confused on how to proceed when I deal only with a user.
This is the whole UserPatientAdd class: https://ideone.com/clUSa3
How can I solve this problem?
You need to set the UserPatient using something like this
In your SharedResources class, create a new method:
public void setUserPatient(UserPatient user) {
userPatient = user;
}
Then in your UserPatientAdd class set the new object:
UserPatient userPatient = new UserPatient (birth, name, bloodType, bloodPressure, cbpm, vacinesTaken, vacinesToBeTaken,
allergies,weight, height, surgeries, desease);
SharedResources.getInstance().setUserPatient(userPatient);
Done

Using variables from another method - problems understanding the object orientation

the following code is incomplete but the main focus of my question is on the method processConfig() anyway. It reads the properties out of a file and I want to handover these properties to the method replaceID(). It worked already when the content of processConfig was in the main()-method. But now I wanted to put this code into it´s own method. What is the best way of handing over the properties (which I saved in Strings like difFilePath). I´m not that familiar with OO-programming and want to understand the concept. Thanks for your help.
public class IDUpdater {
....
public static void main(String[] args) throws Exception {
//Here I want to call the variables from processConfig() to make them available for replaceID(...)
replaceID(difFilePath, outputDifPath, encoding);
}
public static void replaceID(String difFilePath, String outputDifPath, String encoding) throws Exception{
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
String difFilePath = prop.getProperty("dif_file_path");
String outputDifPath = prop.getProperty("output_dif_path");
String encoding = prop.getProperty("encoding");
}
}
You've to declare your variables globally. This way they can be accessed in each method. After you've declared them globally you first call your processConfig in your main method, which will set your variables to what they should be.
public class IDUpdater {
private String difFilePath;
private String outputDifPath;
private String encoding;
public void main(String[] args) throws Exception {
processConfig();
replaceID();
}
public void replaceID() throws Exception{
// You can use your variables here.
return record;
}
public void processConfig(){
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (Exception e) {
logger.error("File 'config.properties' could not be found.");
}
try {
prop.load(input);
} catch (Exception e) {
logger.error("Properties file could not be loaded.");
}
difFilePath = prop.getProperty("dif_file_path");
outputDifPath = prop.getProperty("output_dif_path");
encoding = prop.getProperty("encoding");
}
}
Note that I declared the variables privately. For more information about protecting your variables see https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx.
You may want to read an article (or even better yet - a book) on topic of encapsulation and objects. This or this may be a good starting point for you. There is no point in anyone fixing your code, if you don't understand the concepts behind it.

How to save a whole stack/list/array (some sort of multiple data structure) to a text document

I'm trying to create a rudimentary history system for a web browser I'm designing, unfortunately, I can only find ways to either store 1 web address for a history, or not at all, the fileWriter and fileOutputStream seem to limit to one single item per write, which would overwrite the previous if I tried to output one at a time.
I would appreciate it if people could either suggest ways to store an entire list of strings in an external txt doc, bonus points if you can retain an order to them
request for code:
private void loadWebPage(String userInput) {
if (stackTest == true) {
forwardStack.push(urlBox.getText());
stackTest = false;
} else {
backStack.push(urlBox.getText());
}
try {
createHistory(urlBox.getText());
// displays the content of a html link in the web window, as per
// user input
webWindow.setPage(userInput);
// sets the text in the urlbox to the user input so they can check
// at any time what page they are on
urlBox.setText(userInput);
} catch (Exception e) {
// if user enters a bad url then produce error
try {
File file = new File(userInput);
webWindow.setPage(file.toURI().toURL());
} catch (Exception e1) {
System.out.println("Error 001: Bad URL");
}
}
}
private void createHistory(String webAddress) {
JMenuItem button = new JMenuItem(webAddress);
history.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent histPress) {
loadWebPage(webAddress);
historyStack.push(webAddress);
try {
FileWriter writer = new FileWriter(histPath, false);
writer.write(historyStack);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void recoverHistory() {
//this will read from the txt doc and create a
//history based on past uses of the browser
}
FileWriter will not store any data construct and will overwrite each value if done using string and forLoop
I hope someone knows the answer

Reading an object from a file, than add to an arraylist

Now i'm working on a school assignment for java binary I/O.
i have to write some Restaurant dishes, write those to a file. also i have to read these objects from the file.
for now i got it working that i write dishes to the file using this piece of code
private ArrayList<Gerecht> gerechten;
public void writeToFile() throws FileNotFoundException, IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("Menu.txt"));
out.writeBytes(gerechten.toString());
} // catch any file creation errors
catch (FileNotFoundException e) {
System.out.println("Error opening file: Menu.txt");
} catch (IOException e) {
System.out.println("Error writing file: Menu.txt");
}
}
An "Gerecht" Object contains:
A name = naam.
a Price = prijs.
Callories = calorien.
public abstract class Gerecht extends Menu{
private String naam;
private double prijs;
private int calorien;
public Gerecht(String naam, double prijs, int calorien) {
this.naam = naam;
this.prijs = prijs;
this.calorien=calorien;
}
When i create an object with the constructor above i get this kind of output.
Screenshot: http://gyazo.com/37d8238aa8b35cb0da06e0d4fca10fa0
ignore the 4th line of all Dishes in the Arraylist, this has to do with super/subclasses.
now i have to read this output, and create objects of them. for example: i would manualy type another dish in the file, with the same layout, there should be 4 objects instead of 3.
i know this post is long, but i have been stuck for a few days now!
You either need:
to parse the written string and manually create an object or
take advantage of object serialization:
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Menu.txt"));
out.writeObject(gerechten);
} // catch any file creation errors
catch (FileNotFoundException e) {
System.out.println("Error opening file: Menu.txt");
} catch (IOException e) {
System.out.println("Error writing file: Menu.txt");
}

Csv file is empty when I writing content

I am trying write to a csv file. After the execution of the code bellow the csv file is still empty.
File is in folder .../webapp/resources/.
This is my dao class:
public class UserDaoImpl implements UserDao {
private Resource cvsFile;
public void setCvsFile(Resource cvsFile) {
this.cvsFile = cvsFile;
}
#Override
public void createUser(User user) {
String userPropertiesAsString = user.getId() + "," + user.getName()
+ "," + user.getSurname() +"\n";;
System.out.println(cvsFile.getFilename());
FileWriter outputStream = null;
try {
outputStream = new FileWriter(cvsFile.getFile());
outputStream.append(userPropertiesAsString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public List<User> getAll() {
return null;
}
}
This is a part of beans.xml.
<bean id="userDao" class="pl.project.dao.UserDaoImpl"
p:cvsFile="/resources/users.cvs"/>
Program compiles and doesn't throw any exceptions but CSV file is empty.
If you're running your app in IDE, the /webapp/resources used for running app will differ from the /webapp/resources in your IDE. Try to log full path to file and check there.
try using outputStream.flush() as the final statement in the first of the try block.
I think you're looking at the wrong file. If you specify an absolute path /resources/users.cvs, then it probably won't be written into the a folder relative to the webapp. Instead, it will be written to /resources/users.cvs
So the first step is to always log an absolute path to make sure the file is where you expect it.
Try with this code, it will at least tell you where the problem lies (Java 7+):
// Why doesn't this method throw an IOException?
#Override
public void createUser(final User user)
{
final String s = String.format("%s,%s,%s",
Objects.requireNonNull(user).getId(),
user.getName(), user.getSurname()
);
// Note: supposes that .getFile() returns a File object
final Path path = csvFile.getFile().toPath().toAbsolutePath();
final Path csv;
// Note: this supposes that the CSV is supposed to exist!
try {
csv = path.toRealPath();
} catch (IOException e) {
throw new RuntimeException("cannot locate CSV " + path, e);
}
try (
// Note: default is to TRUNCATE the destination.
// If you want to append, add StandardOpenOption.APPEND.
// See javadoc for more details.
final BufferedWriter writer = Files.newBufferedWriter(csv,
StandardCharsets.UTF_8);
) {
writer.write(s);
writer.newLine();
writer.flush();
} catch (IOException e) {
throw new RuntimeException("write failure", e);
}
}

Categories

Resources