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.

Slides:



Advertisements
Similar presentations
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Advertisements

Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
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.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
18 File handling1June File handling CE : Fundamental Programming Techniques.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
Introduction to Java Files. Text Files A sequential collection of data stored on a permanent storage device Hard drive USB memory CD/DVD Has a name and.
Lecture 2 Objectives Learn about objects and reference variables.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Building Java Programs File Processing. 2 Input/output (I/O) import java.io.*; Create a File object to get info about a file on your drive. –(This doesn't.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4.
Objectives  File I/O: using Scanner with File  Inserting into Partially Filled Array  Deleting from Partially Filled Array  Static methods and variables.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
CS1020 Data Structures and Algorithms I Lecture Note #16 File Processing.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
Streams & File Input/Output (I/O)
Chapter 6 Loops and Files
CMSC 202 Text File I/O.
Reading from a file and Writing to a file
Java Programming Lecture 2
Streams and File I/O.
Building Java Programs
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
CSS161: Fundamentals of Computing
Interactive I/O Input from keyboard Must prompt user User friendly
Building Java Programs
Building Java Programs Chapter 6
Building Java Programs Chapter 6
Building Java Programs
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
File Handling in Java January 19
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
CIS 110: Introduction to Computer Programming
Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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

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

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

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

Reading a file with Scanner Scanner = new Scanner(new File(" ")); 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( ); }

Token-based processing nextInt nextDouble next

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

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

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 {