Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering...
-
Upload
blaze-hood -
Category
Documents
-
view
218 -
download
1
Transcript of Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering...
Advantages of files
• Can edit data, prepare ahead of time• Can rerun file without reentering data• Can examine output at leisure • Can display output to screen or print• Can use output as input into another
program– means of communicating between
programs
files
• naming rules(dos) - 1 to 8 character name, optionally followed by a period and up to a 3 character extension
• extension indicates the type of file by convention– .java – java source code file– .cpp – c++ program file– .doc,.docx – Word file– .exe – executable file– .pdf – Adobe Portable Document File– .txt - Text files(ASCII form, printable)– .dat - data files – attackers can easily change the extension of a file to bypass a security check
Text file
• composed of characters only• .txt• Differs from .doc file• Size of file• Can be created in notepad, wordpad
Accessing file from a Java Program
• Create an object• File class• Pass the name of the file, including path• File f = new File(name);• File f = new File (“c:\\temp\\junk.txt”);
import java.io.*; // for File
public class FileInfo
{
public static void main (String[] args)
{
File f = new File ("hamlet.txt");
System.out.println("exists returns " + f.exists());
System.out.println("can read returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
}
}
Sample Output
No file
exists returns false
can read returns false
length returns 0
getAbsolutePath returns C:\Documents and Settings\csuser\junk.txt
junk.txt: This is a test.
exists returns true
can read returns true
length returns 15
getAbsolutePath returns C:\Documents and Settings\csuser\junk.txt
Method Description
delete() Deletes the given file
exists() Returns whether or not this file exists on the system
getAbsolutePath() Returns the full path where this file is located
getName() Returns the name of this file as a string
isDirectory() Returns whether this file is a directory/folder
isFile() Returns whether this file is a file
length() Returns the number of characters in the file
mkdirs() Creates the directory represented by this file, if it doesn’t exist
renameTo(file) Changes current file name to arg
Reading a file with ScannerScanner <name> = new Scanner(new File("<file name>"));
• Construct a Scanner that reads from the console:• Scanner console = new Scanner(System.in);//keyboard• Construct a Scanner that reads from the file:
– 1. create a File object (or stream)• File f = new FileReader(“junk.txt”);
– 2. create a Scanner object and pass the File object as a parameter
• Scanner inFile = new Scanner(f);
• Or– Scanner inFile = new Scanner(new FileReader(“junk.txt”));
File not found
• Checked exception – exception that must be caught or specifically declared in the header of the method that might generate it
• throws Clause – A declaration that a method will not attempt to handle a particular type of exception
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader(“junk.txt”));
import java.io.*; // for File
import java.util.*; // for Scanner
public class CountWords
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner inFile = new Scanner(new FileReader(“junk.txt”)); //open
String word;
int count = 0;
while (inFile.hasNext()) //check
{
word = inFile.next(); //get
count++; //body
}
System.out.println("total words = " + count);
}
while (inFile.hasNext())
{
word = inFile.next();
count++;
}
extra = inFile.next();
// causes NoSuchElementException
• Error– Scanner inFile = new Scanner(“junk.txt”);
• Must create new file object and Scanner object– File f = new FileReader(“junk.txt”);– Scanner inFile = new Scanner(f);
• Or– Scanner inFile = new Scanner(new File(“junk.txt”));
File i/o:
1. Import the necessary classes from java.util and java.io.
import java.util.*;import java.io.*;
2. Create and associate the appropriate objects with the input/output sources.Scanner inFile = new Scanner(new FileReader(filename));PrintWriter outFile = new PrintWriter(filename);
3. Use the appropriate methods associated with the variables created in Step 2 to input/output the data.
some_input_var = inFile.next(); outFile.println(some_output_var);
4. Close the files. Security Rule: Ensure all resources are properly closed when they are no longer needed
inFile.close(); outFile.close();
Example: import java.util.*;import java.io.*;public class FileClass{ public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileReader ("c:\\temp\\data.txt")); PrintWriter outFile = new PrintWriter("c:\\temp\\results.txt"); int num1; int num2; int sum; num1 = inFile.nextInt(); num2 = inFile.nextInt(); sum = num1 + num2; outFile.println("The sum is " + sum); inFile.close(); outFile.close( ); }}
Example: import java.util.*;import java.io.*;public class ShowSum{ public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileReader (“numbers.dat")); double next; double sum = 0.0; int count = 0; while (inFile.hasNextDouble()) { next = inFile.nextDouble(); count++; sum += next; } System.out.println(“Sum” + sum); inFile.close();}
import java.util.*;import java.io.*;public class ShowSum{ public static void main(String [] args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.println(“What is the file name?”); String fileName = console.nextLine; Scanner inFile = new Scanner(new FileReader(fileName)); double next; double sum = 0.0; int count = 0; while (input.hasNextDouble()) { next = inFile.nextDouble(); count++; sum += next; } System.out.println(“Sum” + sum); inFile.close();}
Input the file name
Line based processingimport java.util.*;import java.io.*;public class EchoUpper{ public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileReader(“poem.txt")); String text; while (inFile.hasNextLine()) { text = inFile.nextLine(); System.out.println(text.toUpperCase()); } inFile.close();}
Opening files
• open the files before using any input or output
• Creates object for physical file • Input file
– If the input file does not exist, open is not successful
• Output file– If the output file does not exist, a new file with
that name is created – If the output file already exists, it is erased
import java.io.*;public class HelloF{ public static void main(String [] args) throws
FileNotFoundException { PrintWriter outFile = new PrintWriter(new File (“hello.txt”)); outFile.println(“Hello world”); outFile.println(); outFile.println(“This program produces”); outFile.println(“four lines of output”); outfile.close(); }}
Replacing throws FileNotFoundException in main
Scanner input;
try
{
input = new Scanner (new FileReader (“numbers.dat”);
}
catch (FileNotFoundException e)
{
System.out.println(“File not found”);
}
Exceptions
• Events that occur during the execution of a program that disrupts the normal flow of instructions.– Exception - an object that represents a program
error. Programs that contain invalid logic cause ("throw") exceptions. • example, trying to read a file that does not exist
– Checked exception - an error that Java forces to be handled in a program; otherwise the program will not compile.
• example (file I/O)
Options: • 1. (catch) Declare that the program will
handle ("catch") the exception try {
inputFile = new Scanner(new FileReader(someFile)); } catch (FileNotFoundException e) {
System.out.println("--- File Not Found! ---"); fileOpened = false;
}
• 2. (throw) states that we choose not to handle the exception, and we accept that our program will crash if an exception occurs
• public static void main(String[] args)throws FileNotFoundException {