Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output.

Similar presentations


Presentation on theme: "Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output."— Presentation transcript:

1 Files

2 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

3 files naming rules(dos) - 1 to 8 character name, optionally followed by a period and up to a 3 character extension 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 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

4 Text file composed of characters only composed of characters only.txt.txt Differs from.doc file Differs from.doc file Size of file Size of file Can be created in notepad, wordpad Can be created in notepad, wordpad

5 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”);

6 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()); }

7 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

8 MethodDescription 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

9 Reading a file with Scanner Construct a Scanner that reads from the console: Scanner console = new Scanner(System.in);//keyboard Construct a Scanner that reads from the file: –File f = new File(“junk.txt”); –Scanner inFile = new Scanner(f); Or –Scanner inFile = new Scanner(new File(“junk.txt”));

10 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 File(“junk.txt”));

11 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 File(“junk.txt”)); //open String word; int count = 0; while (inFile.hasNext()) //check { word = inFile.next(); //get count++; //body } System.out.println("total words = " + count); }

12 while (inFile.hasNext()) { word = inFile.next(); count++; } extra = inFile.next(); // causes NoSuchElementException

13 Error –Scanner inFile = new Scanner(“junk.txt”); Must create new file object and Scanner object –File f = new File(“junk.txt”); –Scanner inFile = new Scanner(f); Or –Scanner inFile = new Scanner(new File(“junk.txt”));

14 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 File(filename)); PrintStream outFile = new PrintStream(new File(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();

15 Example: import java.util.*; import java.io.*; public class FileClass { public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new File ("c:\\temp\\data.txt")); PrintStream outFile = new PrintStream(new File("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( ); }

16 If using \ must use \\ Scanner inFile = new Scanner(new File ("c:\\temp\\data.txt")); PrintStream outFile = new PrintStream("c:\\temp\\results.txt"); Or use / Scanner inFile = new Scanner(new File ("c:/temp/data.txt")); PrintStream outFile = new PrintStream("c:/temp/results.txt");

17 Token-based processing nextInt nextDouble next

18 Example: import java.util.*; import java.io.*; public class ShowSum { public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new File (“numbers.dat")); //start double next; double sum = 0.0; int count = 0; while (inFile.hasNextDouble()) //check { next = inFile.nextDouble(); //get count++; //body or action sum += next; } System.out.println(“Sum” + sum); inFile.close(); }

19 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 File(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

20 Line based processing import java.util.*; import java.io.*; public class EchoUpper { public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new File(“poem.txt")); String text; while (inFile.hasNextLine()) { text = inFile.nextLine(); System.out.println(text.toUpperCase()); } inFile.close(); }

21 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

22 import java.io.*; public class HelloF { public static void main(String [] args) throws FileNotFoundException { PrintStream outFile = new PrintStream(new File (“hello.txt”)); outFile.println(“Hello world”); outFile.println(); outFile.println(“This program produces”); outFile.println(“four lines of output”); outfile.close(); }

23 try/ catch try { statements } catch (exceptiontype name) { statements }

24 Replacing throws FileNotFoundException in main Scanner input; try { input = new Scanner (new File (“numbers.dat”); } catch (FileNotFoundException e) { System.out.println(“File not found”); }


Download ppt "Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output."

Similar presentations


Ads by Google