File I/O
Using files and filesystems
Java:
Useful API classes:
File[java.sun.com] (SE 1.4.2)
For allowing the user to open and save files, take a look at the [a=http://www.izyt.com/freode/viewtopic.php?topic=20&lang=java]java GUI topic[/a], most nojava GUI topic[www.izyt.com], most notably [a=http://www.izyt.com/freode/viewcode.php?code=52]Opening files with JFileChooser[/a]. Opening files with JFileChooser[www.izyt.com].
Read a file
Last updated at 01:25 PM on Thursday 18th October, 2007 by Isaac Turner
Required classes:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
Read
try
{
// Create a buffered reader for the new file
// This will allow us to read in Strings
BufferedReader in = new BufferedReader(new FileReader(path));
String currentLine;
while((currentLine = in.readLine()) != null)
{
// Do something with the file
System.out.println(currentLine);
}
// Close the file
in.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
Comments (0)
Create a file if it doesn't exist
Last updated at 01:28 PM on Thursday 18th October, 2007 by Administrator
File file = new File(path);
// Does the file already exist
if(!file.exists())
{
try
{
// Try creating the file
file.createNewFile();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
(File).createNewFile() [java.sun.com] will return true if the file was successfully created, false if it already exists.
Comments (0)
Get directory listing
Last updated at 04:10 PM on Wednesday 8th August, 2007 by Administrator
File dir = new File("directory/path");
File[] files = dir.listFiles();
Comments (0)
Write to a file
Last updated at 02:16 PM on Sunday 23rd September, 2007 by Administrator
Required classes:
import java.io.FileWriter;
To write to a file:
try
{
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write(text);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
Comments (0)