Reputation: 37
I am a new java student currently working on File I/O. My professor has asked us to create a very simple "DC universe" game using interfaces and classes and has asked us in the current lab I am working on, to create an instance of an object and then save the file to a directory in our C drive. My problem, is that even after all my constant 2 hours of digging through past topics I still cannot find a proper explanation as to how I create a directory and THEN create a file and write to a file in that directory because it appears whenever I run my code to not be able to do both tasks simultaneously. The code below also contains an error at the "Print Writer" line and asks to add a throw clause for "file not found exception"
Any and all help is vastly appreciated
package runtime;
import java.io.*;
import java.util.*;
import model.hero.*;
public class Gameplay {
public static void main(String[] args) {
File x = new File("C://prog24178//dcheroes.dat");
if(!x.exists()){
x.mkdir();
}
PrintWriter output = new PrintWriter(x);
// 1. Create a save file called dcheroes.dat in {$root}\prog24178
// 2. Create a hero
// 3. Save hero to file
}
}
Upvotes: 1
Views: 236
Reputation: 198304
Two errors I see:
x.mkdir()
will try to create C:\prog24178\dcheroes.dat
as a directory. Use x.getParent().mkdir()
to create C:\prog24178
.
the PrintWriter
error is Java complaining about you not catching a potential error. Your code is fine, it's just Java being demanding. Surround your code with a try { ... } catch (FileNotFoundException ex) { ... }
block. Every function call that could potentionally throw an Exception
needs to have that exception caught, or the containing function needs to be marked to also be a potential source of the exception (and you can't do the latter on main
).
Upvotes: 1