Download here.

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
How to read from a file
Suppose the file is called data.txt and contains the following data
Homer 85
Bart 67
Marge 75
Lisa 95
Krusty 66
Itchy 88
Scratchy 44
Problem: Read the data from the file and print the data on the screen:
1. include import java.io.*
2. attach throws IOException to the main
method heading ( and any other method
that uses file stuff)
3. Make a File object with the name of your
disk file (in this case "data.txt").
import java.io.*;
import java.util.*;
public class FileExample
{
public static void main(String[] args) throws
IOException
{
File inFile = new File("data.txt");
The File object can have any name. I chose
inFile but any name will do.
4. Make sure the file exists
if (!inFile.exists())
{
System.out.println("File does not exist"):
System.exit(0);
}
Scanner input = new Scanner(inFile);
5. Make a Scanner passing it the File object
of step 3 (and not System.in)
6. process the file in a while loop. Use the
hasNext() method.
while (input.hasNext())
7. Perform the task. IN THIS CASE, read
the data and print it to the screen.
{
String name = input.next();
int grade = input.nextInt();
System.out.println(name + " "+grade);
You are using a Scanner here but the data
comes from a file and not the keyboard.
}
8. Close the input stream
input.close()
}
}
How to write to a file.
Use a PrintWriter
We will
• read a name and two numbers from the keyboard and
• write the name and sum of the numbers to a file called results.txt.
Assume that there are 10 names.
Note: This example reads from the keyboard but you could easily read from a file.
1. include import java.io.*
2. attach throws IOException to the main
method heading ( and any other method that
uses file stuff)
3. Make a File object using the name of the
disk file where you want to store the results.
import java.io.*;
import java.util.*;
public class FileExample
{
public static void main(String[] args) throws
IOException
{
Scanner input = new Scanner(System.in);
File outputFile = new File("results.txt");
The program will create this file.
If the file already exists, it will be erased.
4. Make a PrintWriter object passing is the
File object of step 3
PrintWriter pw = new PrintWriter(outpurFile)
5. Now use the Printwriter object just as you
would uses System.out. However, output will
go to a disk file ("results.txt") and not the
screen.
for(int i = 1; i <= 10; i++)
{
String name = input.next();
int num1 = input.nextInt();
int num2 = input.nextInt();
int sum = num1+num2;
pw.println(name + """+ sum);
}
pw.close();
6. close the PrintWriter
}
}