Today I, Lord Berserkguard, protector of the Alliance, am going to show you how to write files in Java – a little more advanced that the basic I/O you know with the console printing.
The class we are going to work with is called FileWriter – you can pretty much tell what it does
We are also going to use a Javax control called JFileChooser as a way for the user to navigate to the file/folder to save. Remember – we have to import javax.swing.* for this to work properly. The program I uploaded already has that import statement, so you don’t need to worry about it for this example.
http://www.box.net/shared/jb0u5k2lhh
Open up that file posted above, and you should see some import statements, a pre-made Frame for you, and an ActionPerformed event. Make a menu bar like you have in the past, with one MenuItem for a save function. Don’t forget to add an action listener to the MenuItem, otherwise it will just look pretty and not actually do anything.
Once you have done that, declare and add a TextArea to the Frame
(HINT: This is declared and used just about exactly the same as a TextField – if you still have trouble I will show you how to do it, there is also a line of commenting ALREADY IN THE PROGRAM which tells you the parameters it takes)
Add this under the if (e.getSource() == saveFile){ in the ActionPerformed:
If the name of your MenuItem isn’t saveFile, than you have to change the name of that to whatever you named your MenuItem.
Declare a string which is set to the User’s current directory:
String wd = System.getProperty("user.dir");
Now, for the JFileChooser implementation – the parameter is the directory to start in, which was set using System.getProperty("user.dir");.
JFileChooser fc = new JFileChooser(wd);
Lastly, to show the dialog, you call the showDialog() command from the JFileChooser
(In this case, it’s named fc)
The command takes 2 parameters (parent and approveButtonText):
The parent parameter isn’t all that important, and for all intensive purposes can just be set to NULL. The second parameter is the text you want the button on the dialog to display.
int rc = fc.showDialog(null, "Save File");
Notice how you see the showDialog returns an integer – this is because the showDialog will return either a 0 or a 1 based on input. We can than use rc to check if the user clicked the “Save File” button or cancelled out of the dialog.
So now we check if the user approved (clicked “Save File”)
Do this by adding this ‘if’ statement:
if (rc == JFileChooser.APPROVE_OPTION){
}
If you wanna get creative, the APPROVE_OPTION could also be something like CANCEL_OPTION or ERROR_OPTION, depends on what you want to check for. For now let’s stick with the APPROVE_OPTION.
In between this ‘if’ statement, declare a File and set it to the file that the user selected from the JFileChooser. getSelectedFile(); returns the file that was selected as type File – which is why we declare it the way we do.
File file = fc.getSelectedFile();
Once you add that, declare a String and set it to the file’s location
(getAbsolutePath() returns the whole file path, for example, “C://Documents and Settings/this.txt”. getName() only returns the file name, as in “that.txt”)
String filename = file.getAbsolutePath();
Now that the String is set to the full path that the user navigated to, we can use it to specify where the file should be written. We have to use a ‘try’ block – all that does is try to do something, and if there is an error, it raises an exception using ‘catch’. Pretty simple, although it throws many people off unless they know what it does. Declare that now by adding these lines:
try{
}
After you’ve done that, we can now attempt to write a file. To do this, we declare a FileWriter, and set the parameter to the path that the user chose with the JFileChooser (in this case, the String named ‘filename’)
FileWriter writer = new FileWriter( filename );
Now that you have initiated a FileWriter, you should close it when you are done with it; otherwise it takes up system resources, which in some cases make the program unresponsive. To close a FileWriter, use the close() command. Since I named my FileWriter writer, I would close it by typing writer.close();
Now you should have a try block with a FileWriter declared and then closed. If you have got that done, there’s only one more thing we have to do with the FileWriter – Write the File! To achieve this, one would use the write() command. Same as the close command, except that this has a parameter – the text to be written to the file. This should be written after the line where you declared the FileWriter, but before the line where you closed the FileWriter. Putting this anywhere else will result in an error.
For instance, writer.write(“I is the hax”); would print ‘I is the hax’ to the file. Now, you can also write Strings to the file. Just set the parameter to a String. writer.write(filename); would write the path of the file to the file, so that if you opened the file it would say something like “C://Documents and Settings/this.txt”.
However, if you want to make it much cooler, keep reading.
Remember that TextArea you placed on the frame earlier? Here’s where that comes into play. To get the text from a TextArea and put it into a string, you use the same command as you would with a TextField. If you forget what this command is, look in earlier programs where you printed the text from inside a TextField to the system console.
After that, try running the program.
Doesn’t work? It shouldn’t.
We still need to do one more thing to get this to work. Remember the ‘try’ block we added earlier? We have to catch exceptions that the FileWriter might raise, otherwise you might get some errors. To do this, we add a catch() block at the end of the try block. Just like with if/else statements, try/catch statements use the same syntax.
Compare the two:
if(this == that){
//do this
} else {
//do that
}
try{
//try this
} catch (){
//catch that
}
See the similarities?
In between the parentheses after catch, we state the exception that we want to check. For FileWriters, this exception is called IOException – which means Input/Output exception. Just like how you name a String or a TextField or anything else, you also give Exceptions names. The name doesn’t really matter – unless you plan on using it.
So now the try statement should look like this, or something similar:
(I named my IOException “ex”)
try{
FileWriter writer = new FileWriter( filename );
writer.write(“anything you want”);
writer.close();
}catch (IOException ex){
}
If you compile/run the program, it should work. If not, ask me and I will come over and help you. Hope this helps!
~Your one and only Lord and Master Berserkguard,
Protector of the Alliance,
Pwner of the n00bs
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment