Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Mridul Gupta
2,144 PointsImport 2 strings and one object from a file??
Referring to my previous question over here https://teamtreehouse.com/community/map-inside-a-map-how-to-load-and-store-values-from-files-using-serialisation
I understood how to use export to file method in my project but now i am facing problem in import because i have 2 strings and 1 object in the file. In the video Craig told to split the string, but here it is generating error because if i split, it doesn't remain an object.
public void importFrom() {
File myFile = new File(mName + ".ser");
try (
FileInputStream fis = new FileInputStream(myFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
) {
String line;
while((line = reader.readLine()) != null) {
String[] args = line.split("\\|");
insertToMap(args[0],args[1],args[2]);
}
} catch(IOException ioe) {
System.out.printf("Problems loading %s %n", myFile);
ioe.printStackTrace();
}
}
I am also including my export method i implemented for reference.
public void exportTo() throws IOException {
File myFile = new File(mName + ".ser");
if (!myFile.exists()) {
myFile.createNewFile();
}
try (
FileOutputStream fos = new FileOutputStream(myFile);
PrintWriter writer = new PrintWriter(fos);
) {
for (Map.Entry<String, Map<String, List<Investment>>> entry1 : mInvestmentMap.entrySet()) {
Map<String, List<Investment>> innerMap = entry1.getValue();
for (Map.Entry<String, List<Investment>> entry2 : innerMap.entrySet()) {
List<Investment> innerList = entry2.getValue();
for (Investment myObject : innerList) {
writer.printf("%s|%s|%s%n",
entry1.getKey(),
entry2.getKey(),
myObject.toString());
}
}
}
} catch (IOException ioe) {
System.out.printf("Problem saving %s.ser %n", mName);
ioe.printStackTrace();
}
}
My InsertToMap method
public void insertToMap(String a, String b, Investment inv) {
if (!mInvestmentMap.containsKey(a)) {
List<Investment> list = new ArrayList<>();
list.add(inv);
Map<String, List<Investment>> innerMap = new HashMap<>();
innerMap.put(b, list);
mInvestmentMap.put(a, innerMap);
} else if (!mInvestmentMap.get(a).containsKey(b)) {
List<Investment> list = new ArrayList<>();
list.add(inv);
mInvestmentMap.get(a).put(b, list);
} else {
mInvestmentMap.get(a).get(b).add(inv);
}
}