Archive:Java File IO: Difference between revisions
wikademia>JWSchmidt |
wikademia>Zchenyu mNo edit summary |
||
| Line 1: | Line 1: | ||
File | File input/output is quite similar to the System.in and System.out that you already have begun using. | ||
=Files= | |||
== Files == | |||
Files are another type of variable. You can make a file like this: | Files are another type of variable. You can make a file like this: | ||
<pre>File f = new File("test.txt")</pre> | <pre>File f = new File("test.txt")</pre> | ||
| Line 13: | Line 14: | ||
For a full list of methods you can use, go to http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html | For a full list of methods you can use, go to http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html | ||
=File Output= | == File Output == | ||
To write to a file, you can use a FileWriter or a FileOutputStream. | To write to a file, you can use a FileWriter or a FileOutputStream. | ||
==FileWriter== | ==FileWriter== | ||
| Line 34: | Line 35: | ||
Of course, you should only use this when you already have a character array. | Of course, you should only use this when you already have a character array. | ||
==FileOutputStream== | === FileOutputStream === | ||
=File Input= | == File Input == | ||
[[Category:Java]] | [[Category:Java]] | ||
Revision as of 20:50, 24 April 2007
File input/output is quite similar to the System.in and System.out that you already have begun using.
Files
Files are another type of variable. You can make a file like this:
File f = new File("test.txt")
This does not return an exception if the file doesn't exist. To check if it does:
f.exists()
This will return a boolean.
To check if it is a file or directory:
f.isFile() f.isDirectory()
For a full list of methods you can use, go to http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html
File Output
To write to a file, you can use a FileWriter or a FileOutputStream.
FileWriter
This class writes strings or char[] to a file. To create one:
FileWriter fw = new FileWriter("test.txt");//Create a filewriter writing to test.txt
FileWriter fw = new FileWriter("test.txt", true);//Do not delete contents of file - append
It is as simple to write. After you create a FileWriter just use:
String s = "Testing" //INITIALIZE FileWriter fw fw.write(s);
FileWriter can also write in other formats. Using char[]:
Char[] charAr=s.toCharArray();//A method in class String fw.write(charAr);
Of course, you should only use this when you already have a character array.