Files are handled in the library io. Instead of needing to type in all input every time you run a program, you can type the input ONCE in a file and read it into your program. You can also send output from your program to a file instead of to the console. This allows you to save it.
The following streams are available in fstream:
BufferedReader input file, you can read from it, but not write to it.
needs to exist before you can open it.
PrintWriter output file, you can write to it but not read from it.
if it doesn’t exist when opened, Java will create it for you.
if it does exist, whatever is in it will be erased.
You open and create a new file stream at the same time. For example:
BufferedReader in = new BufferedReader (new FileReader (“input.txt”));
opens a file called input.txt that is saved in the same directory as the Java program you are writing.
whenever you want to call it later in the program, use the name ‘in’.
PrintWriter out = new PrintWriter(new FileWriter(“output.txt”));
opens a file called output.txt on your floppy drive for writing only
To Read and Write to a file:
String input = in.readLine ();//Reads one line and stores it in input
out.print("Hello, "); //Outputs Hello to the file
out.println("I'm fine"); //Outputs Im fine and an enter
To close your files (this is not necessary, but it is nice style);
in.close();
Another thing that you should note in the program is the use of String input = in.readLine (); while (input != null)Your file is null when there is not more data to read in it. Also, all operations with files need to be guarded with tryécatch blocks.
This code reads a single line from a file and prints it to the screen
public static void main (String args [])
{ readFile ("input.txt"); }
public static void readFile (String filename)
{
BufferedReader in;
try
{
in = new BufferedReader (new FileReader (filename));
String input = in.readLine ();
System.out.println (input);
in.close();
}
catch (IOException e)
{
System.out.println ("Error opening file " + e);
}
}
This code reads in a series of integers, one on each line of the file and enters them into an array.
public static void main (String args [])
{
int a [] = new int [10];
int i = 0;
BufferedReader in;
try
{
in = new BufferedReader (new FileReader ("input.txt"));
String input = in.readLine ();
while (input != null)
{
a [i] = (Integer.parseInt (input));
System.out.println(""+a[i]);
input = in.readLine ();
i++;
}
in.close ();
}
catch (IOException e)
{
System.out.println ("Error opening file " + e);
}
}
This code ouputs some text to a file:
public static void main (String args [])
{ writeFile ("output.txt"); }
public static void writeFile (String filename)
{
PrintWriter out;
try
{
out = new PrintWriter(new FileWriter(filename));
out.print("Hello, ");
out.println("I'm fine");
out.close();
}
catch (IOException e)
{
System.out.println ("Error opening file " + e);
}
}