Jump to content

Archive:Java File IO: Difference between revisions

From IdeaWazaWiki
New page: File Input/Output is similar to the System.out and System.in that you already have begun using. The only difference is that you read from a file. =Files= Files are another type of variable...
 
Line 3: Line 3:
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>
This does not return an exception if the file doesn't exist. To check if it does:
<pre>f.exists()</pre>
This will return a boolean.
To check if it a file or directory:
<pre>f.isFile()
f.isDirectory()
</pre>
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:
<pre>
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
</pre>
It is as simple to write. After you create a FileWriterm just use:
<pre>
String s = "Testing"
//INITIALIZE FileWriter fw
fw.write(s);
</pre>
==FileOutputStream==
=File Input=

Revision as of 14:46, 26 November 2006

File Input/Output is similar to the System.out and System.in that you already have begun using. The only difference is that you read from a file.

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 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 FileWriterm just use:

String s = "Testing"
//INITIALIZE FileWriter fw
fw.write(s);

FileOutputStream

File Input