Issue
I have a javafx homework at school
I was able to save the data as requested
My question is how can I read the data from the Text File so that all the data is back in the right place
Integer cb_years_v;
String cb_manuf_v,smb_type_v,tg_v,cb_extras_v,lv_size_v,tf_vend_user_v,tf_vend_name_v,pf_pass_v,ta_other_v,price_value_v;
cb_manuf_v = cb_manuf.getValue(); //ComboBox
smb_type_v=ch_type.getText(); //SplitMenuButton
tg_v = tg.getSelectedToggle().toString(); //ToggleGroup
cb_extras_v = cb_extras.getValue(); //ComboBox
cb_years_v = cb_years.getValue(); //ComboBox
lv_size_v = lv_size.getSelectionModel().getSelectedItem().toString(); //ListView
tf_vend_name_v = tf_vend_name.getText(); //TextField
tf_vend_user_v = tf_vend_user.getText(); //TextField
pf_pass_v = pf_pass.getText(); //PasswordField
ta_other_v = ta_other.getText(); //TextArea
price_value_v = price_value.getText(); //Label
FileChooser chooser = new FileChooser();
chooser.setTitle("Choose location To Save Report");;
File selectedFile = null;
while(selectedFile== null){
selectedFile = chooser.showSaveDialog(null);
}
File file2 = null;
file2 = selectedFile;
PrintWriter outFile = null;
try {
outFile = new PrintWriter(file2);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
outFile.println("Manufacturer = " + cb_manuf_v);
outFile.println("Type = "+smb_type_v);
outFile.println("Color = " +tg_v);
outFile.println("Extras = " + cb_extras_v);
outFile.println("Year = " + cb_years_v);
outFile.println("Size = " + lv_size_v);
outFile.println("Vendor Name = " + tf_vend_name_v);
outFile.println("Vendor User = " + tf_vend_user_v);
outFile.println("Password = " + pf_pass_v);
outFile.println("Other = " + ta_other_v);
outFile.println("Price = " + price_value_v);
outFile.close();
Thank you for your help!
Solution
Here is another way you could do it. Instead of using Scanner
, you could use Files.readAllLines
. From there, you can use the line index as the control in a Switch-Statement
or if a line contains the info you need to extract using an If-Statement
. This example does not show the Switch-Statement
version. It only shows the If-Statement
version. I did not test this code so there may be errors.
try {
File selectedFile = new File("");
List < String > lines = Files.readAllLines(selectedFile.toPath());
for (String line: lines) {
if (line.contains("Manufacturer")) {
cb_manuf.setValue(line.split("=")[1].strip());
} else if (line.contains("Type")) {
smb_type.setText(line.split("=")[1].strip());
} else if (line.contains("Color")) {
...
} else if (line.contains("Extras")) {
...
} else if (line.contains("Year")) {
...
} else if (line.contains("Size")) {
...
} else if (line.contains("Vendor Name")) {
...
} else if (line.contains("Vendor User")) {
...
} else if (line.contains("Password")) {
...
} else if (line.contains("Other")) {
} else if (line.contains("Price")) {
...
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Answered By - Sedrick