Presentation is loading. Please wait.

Presentation is loading. Please wait.

Streams and File. 1. Introduction Data stored in variables and arrays is temporary For long-term retention of data, even after the programs that create.

Similar presentations


Presentation on theme: "Streams and File. 1. Introduction Data stored in variables and arrays is temporary For long-term retention of data, even after the programs that create."— Presentation transcript:

1 Streams and File

2 1. Introduction Data stored in variables and arrays is temporary For long-term retention of data, even after the programs that create the data terminate, computers use files. Data maintained in files is persistent data—it exists beyond the duration of program execution. In this chapter, we explain how Java programs create, update and process files.

3 2. Files and Streams Java views each file as a sequential stream of bytes. Every operating system provides a mechanism to determine the end of a file, such as an end-of-file marker. A Java program processing a stream of bytes simply receives an indication from the operating system when it reaches the end of the stream— the program does not need to know how the underlying platform represents files or streams.

4 Byte-Based and Character-Based Streams File streams can be used to input and output data as bytes or characters. Byte-based streams input and output data in its binary format. Character-based streams input and output data as a sequence of characters. If the value 5 were being stored using a byte-based stream, it would be stored in the binary format of the numeric value 5, or 101. If the value 5 were being stored using a character- based stream, it would be stored in the binary format of the character 5, or 00000000 00110101 (this is the binary representation for the numeric value 53, which indicates the Unicode® character 5).

5 The difference between the two forms is that the numeric value can be used as an integer in calculations, whereas the character 5 is simply a character that can be used in a string of text Files that are created using byte-based streams are referred to as binary files, while files created using character-based streams are referred to as text files. Text files can be read by text editors, while binary files are read by programs that understand the file’s specific content and its ordering.

6 Standard Input, Standard Output and Standard Error Streams A Java program opens a file by creating an object and associating a stream of bytes or characters with it. Java can also associate streams with different devices. When a Java program begins executing, in fact, it creates three stream objects that are associated with devices— System.in, System.out and System.err. System.in (the standard input stream object) normally enables a program to input bytes from the keyboard

7 object System.out (the standard output stream object) normally enables a program to output character data to the screen Object System.err (the standard error stream object) normally enables a program to output character-based error messages to the screen. Each stream can be redirected. For System. in, this capability enables the program to read bytes from a different source. For System. out and System.err, it enables the output to be sent to a different location, such as a file on disk. Class System provides methods setIn, setOut and setErr to redirect the standard input, output and error streams, respectively.

8 The java.io Package Java programs perform file processing by using classes from package java.io. This package includes definitions for stream classes, such as FileInputStream (for byte- based input from a file), FileOutputStream (for byte-based output to a file), FileReader (for character- based input from a file) and FileWriter (for character-based output to a file), which inherit from classes InputStream, OutputStream, Reader and Writer, respectively.

9 Java contains classes that enable you to perform input and output of objects or variables of primitive data types. The data will still be stored as bytes or characters behind the scenes, allowing you to read or write data in the form of ints, Strings, or other types without having to worry about the details of converting such values to byte format. To perform such input and output, objects of classes ObjectInputStream and ObjectOutput- Stream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream

10 Java offers many classes for performing input/output operations. In addition to the java.io classes, character- based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard—it can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf.

11 3. Class File class File, which is useful for retrieving information about files or directories from disk. Objects of class File do not open files or provide any file-processing capabilities. However, File objects are used frequently with objects of other java.io classes Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name.

12 The constructor with two String arguments specifies an absolute or relative path as the first argument and the file or directory to associate with the File object as the second argument. The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument. The fourth constructor uses a URI object to locate the file. A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites.

13 For example, http://www.deitel.com/ is the URL for the Deitel & Associates website. URIs for locating files vary across operating systems. On Windows platforms, the URI file://C:/data.txt identifies the file data.txt stored in the root directory of the C file://C:/data.txt Figure 17.2 lists some common File methods.

14

15 // Fig. 17.3: FileDemonstration.java // File class used to obtain file and directory information. import java.io.File; import java.util.Scanner; public class FileDemonstration { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); System.out.print( "Enter file or directory name: " ); analyzePath( input.nextLine() ); } // end main

16 // display information about file user specifies public static void analyzePath( String path ) { // create File object based on user input File name = new File( path ); if ( name.exists() ) // if name exists, output information about it { // display file (or directory) information System.out.printf(

17 "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n %s%s", name.getName(), " exists", ( name.isFile() ? "is a file" : "is not a file" ), ( name.isDirectory() ? "is a directory" : "is not a directory" ), ( name.isAbsolute() ? "is absolute path" : "is not absolute path" ), "Last modified: ", name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent() );

18 if ( name.isDirectory() ) // output directory listing { String[] directory = name.list(); System.out.println( "\n\nDirectory contents:\n" ); for ( String directoryName : directory ) System.out.println( directoryName ); } // end if } // end outer if else // not file or directory, output error message { System.out.printf( "%s %s", path, "does not exist." ); } // end else } // end method analyzePath } // end class FileDemonstration

19 4.Sequential-Access Text Files We begin with text files, enabling the reader to quickly create and edit human-readable files. We discuss creating, writing data to, reading data from and updating sequential- access text files. Creating a Sequential-Access Text File Java imposes no structure on a file—notions such as records do not exist as part of the Java language. Therefore, you must structure files to meet the requirements of your applications.

20 4.1. Creating a text file with the object of the Formatter class 1.//FileTest.java 2.import java.util.Formatter; 3.import java.io.FileNotFoundException; 4.import java.util.Scanner; 5. public class FileTest 6.{ 7.public static void main(String[] args) 8.{ 9.CreateFile app1= new CreateFile(); 10.app1.openFile(); 11.app1.addRecord(); 12.app1.closeFile(); 13.} 14.}

21 15.class CreateFile 16.{ 17.private Formatter output; 18.private Scanner input; 19.public void openFile() 20.{ 21.try{ 22.output=new Formatter("client.txt"); 23.} 24.catch( FileNotFoundException fileNotFoundException ) 25.{ 26.System.err.println("Error in opening or craeting file"); 27.System.exit(1); 28.} 29.}

22 30.public void addRecord() 31.{ 32.input =new Scanner(System.in); 33.System.out.println("enter First_Name:"); 34.String firstName=input.next(); 35.System.out.println("enter Last_Name:"); 36.String lastName=input.next(); 37.System.out.println("enter Balance:"); 38.Double balance= input.nextDouble(); 39.output.format("%s %s %.2f\r\n",“Alemu",“Mamo",4605.50); 40.output.format("%s %s %.2f\r\n”,”Genene”,"Birhanu",3820.50); 41.output.format("%s %s %.2f\r\n",firstName,lastName,balance); 42.}

23 43.public void closeFile() 44.{ 45.if(output!=null) 46.{ 47.output.close(); 48.} 49.} 50.}

24 output is a Formatter variable a Formatter object outputs formatted Strings, using the same formatting capabilities as method System.out.printf. A Formatter object can output to various locations, such as the screen or a file The constructor used in line 22 takes one argument—a String containing the name of the file, including its path. If a path is not specified, as is the case here, the JVM assumes that the file is in the directory from which the program was executed.

25 If the file does not exist, it will be created. If an existing file is opened, its contents are truncated—all the data in the file is discarded. At this point(Line 22) the file is open for writing, and the resulting Formatter object can be used to write data to the file. Lines 24–28 handle the FileNotFoundException, which occurs if the file does not exist and a new file cannot be created. This exception may also occur if there’s an error opening the file.

26 we call static method System.exit and pass the value 1. This method terminates the application. An argument of 0 to method exit indicates successful program termination. A nonzero value, such as 1 in this example, normally indicates that an error has occurred. This value is passed to the command window that executed the program. The argument is useful if the program is executed from a batch file on Windows systems or a shell script on UNIX/ Linux/Mac OS X systems. Batch files and shell scripts offer a convenient way of executing several programs in sequence. When the first program ends, the next program begins execution. It’s possible to use the argument to method exit in a batch file or shell script to determine whether other programs should execute.

27 The record’s information is written to clients.txt (lines 39-40) using method format, which can perform identical formatting to the System.out.printf Method format outputs a formatted String to the output destination of the Formatter object—the file clients.txt. The format string "%s %s %.2f\n" indicates that the current record will be stored as a String (the first name), another String (the last name) and a floating- point value (the balance). Each piece of information is separated from the next by a space, and the double value (the balance) is output with two digits to the right of the decimal point (as indicated by the.2 in %.2f).

28 [Note: You can also output data to a text file using class java.io.PrintWriter, which provides format and printf methods for outputting formatted data.] Line 47 closes the object by simply calling method close. If method close is not called explicitly, the operating system normally will close the file when program execution terminates—this is an example of operating- system “housekeeping.” However, you should always explicitly close a file when it’s no longer needed.

29 Platform-Specific Line-Separator Characters different platforms use different line-separator characters. On UNIX/ Linux/Mac OS X, the line separator is a newline (\n). On Windows, it’s a combination of a carriage return and a line feed— represented as \r\n. The method System.out.println outputs a platform- specific line separator after its argument. Also, regardless of the line separator used in a text file, a Java program can still recognize the lines of text and read them.

30 4.2. Reading Data from a Sequential-Access Text File This section shows how to read data sequentially from a text file and we demonstrate how class Scanner can be used to input data from a file rather than the keyboard.

31 1.//FileRead.java 2.import java.util.Scanner; 3.import java.io.File; 4.import java.io.FileNotFoundException; 5.public class FileRead 6.{ 7.public static void main(String[] args) 8.{ 9.try 10.{ 11.Scanner input =new Scanner(new File("client.txt"));

32 12.while(input.hasNext()){ 13.String First_Name=input.next(); 14.String last_Name=input.next(); 15.double balance=input.nextDouble(); 16.System.out.printf("%S %s %.2f\n",First_Name,last_Name,balance); 17.} 18.} 19.catch(FileNotFoundException e){ 20.System.err.println("Error!"); 21.System.exit(1); 22.} 23.} 24.}

33 The file is opened for reading by instantiating a Scanner object in line 11. We pass a File object to the constructor, which specifies that the Scanner object will read from the file "clients.txt" located in the directory from which the application executes. If the file cannot be found, a FileNotFoundException occurs. The exception is handled in lines 19–22.

34 Lines 12–17 read data from the file until the end-of-file marker is reached (in which case, method hasNext will return false at line 12). If no exceptions occur, the record’s information is displayed on the screen Each iteration of the loop inputs one line of text from the text file, which represents one record. define method closeFile, which closes the Scanner (recommended).

35 Reading in int’s Scanner inFile = new Scanner(new File(“in.txt")); int number; while (inFile.hasInt()) { number = inFile.nextInt(); // … }

36 Reading in lines of characters Scanner inFile = new Scanner(new File(“in.txt")); String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); // … }

37 Multiple types on one line // Name, id, balance Scanner inFile = new Scanner(new File(“in.txt")); while (inFile.hasNext()) { name = inFile.next(); id = inFile.nextInt(); balance = inFile.nextFloat(); // … new Account(name, id, balance); } -------------------- String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); Scanner parseLine = new Scanner(line) // Scanner again! name = parseLine.next(); id = parseLine.nextInt(); balance = parseLine.nextFloat(); // … new Account(name, id, balance); }

38 Multiple types on one line // Name, id, balance Scanner inFile = new Scanner(new File(“in.txt")); String line; while (inFile.hasNextLine()) { line = inFile.nextLine(); Account account = new Account(line); } -------------------- public Account(String line) // constructor { Scanner accountLine = new Scanner(line); _name = accountLine.next(); _id = accountLine.nextInt(); _balance = accountLine.nextFloat(); }

39 Streams Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) – it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program – System.in is an input stream Output stream: a stream that accepts output from a program – System.out is an output stream A stream connects a program to an I/O object – System.out connects a program to the screen – System.in connects a program to the keyboard

40 6.Additional java.io Classes This section overviews additional interfaces and classes (from package java.io) for character-based input and output streams. Important classes for text file output (to the file) – PrintWriter – FileOutputStream [ or FileWriter] Important classes for text file input (from the file): – BufferedReader – FileReader FileOutputStream and FileReader take file names as arguments.

41 To use these classes your program needs a line like the following: import java.io.*; Text File Output To open a text file for output: connect a text file to a stream for writing PrintWriter outputStream = new PrintWriter(new FileOutputStream("out.txt")); Similar to the long way: FileOutputStream s = new FileOutputStream("out.txt"); PrintWriter outputStream = new PrintWriter(s); FileOutputStream “connects” PrintWriter to a text file.

42 Output File Streams PrintWriter FileOutputStream Disk Memory out1 smiley.txt PrintWriter out1 = new PrintWriter( new FileOutputStream(“smiley.txt”) );

43 import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class WriteFile5 { public static void main(String[] args) { WriteFile6 file1=new WriteFile6(); file1.openFile(); file1.addRecord(); file1.close(); }

44 class WriteFile6 { private PrintWriter out1; public void openFile() { try { out1=new PrintWriter(new FileOutputStream("Comp1.txt")); } catch(FileNotFoundException e) { System.err.println("ERorr!"); } public void addRecord() { Scanner inp1=new Scanner(System.in); System.out.println("Enter first name:"); String fn=inp1.nextLine(); System.out.println("Enter Last name:");

45 String ln=inp1.nextLine(); System.out.println("Enter Salary:"); double sal=inp1.nextDouble(); out1.format("%s %s %.2f\r\n","Abebe","Getachew",2786.56); out1.println("Adnew Admasu"+sal); out1.print("Damte Habte 675.89\r\n"); out1.format("%s %s %.2f\r\n","Kebede","Belachew",345.78); out1.format("%s %s %.2f",fn,ln,sal); } public void close() { if(out1!=null) { out1.close(); }

46 Overwriting a File Opening an output file creates an empty file Opening an output file creates a new file if it does not already exist Opening an output file that already exists eliminates the old file and creates a new, empty one – data in the original file is lost To see how to check for existence of a file, see the section of the text that discusses the File class.

47 Java Tip: Appending to a Text File To add/append to a file instead of replacing it, use a different constructor for FileOutputStream: outputStream = new PrintWriter(new FileOutputStream("out.txt", true)); Second parameter: append to the end of the file if it exists.

48 Lab Assignment Write a sample code for letting user tell whether to replace or append: System.out.println("A for append or N for new file:"); char ans = keyboard.next(); boolean append = (ans == 'A' || ans == 'a'); outputStream = new PrintWriter( new FileOutputStream("out.txt", append)); true if user enters 'A' hint

49 Closing a File An output file should be closed when you are done writing to it (and an input file should be closed when you are done reading from it). Use the close method of the class PrintWriter (BufferedReader also has a close method ). For example, to close the file opened in the previous example: outputStream.close(); If a program ends normally it will close any files that are open.

50 FAQ: Why Bother to Close a File? If a program automatically closes files when it ends normally, why close them with explicit calls to close? Two reasons: 1. To make sure it is closed if a program ends abnormally (it could get damaged if it is left open). 2. A file opened for writing must be closed before it can be opened for reading.

51 Text File Input To open a text file for input: connect a text file to a stream for reading a BufferedReader object, which uses FileReader to open a text file – FileReader “connects” BufferedReader to the text file For example: BufferedReader smileyInStream = new BufferedReader(new FileReader(“smiley.txt")); Similarly, the long way: FileReader s = new FileReader(“smiley.txt"); BufferedReader smileyInStream = new BufferedReader(s);

52 Input File Streams BufferedReader FileReader Disk Memory inp1 smiley.txt BufferedReader inp1= new BufferedReader( new FileReader(“smiley.txt”) );

53 import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; import java.util.StringTokenizer; //import java.io.File; public class ReadFile4 { public static void main(String[] args) { try{ BufferedReader inp1=new BufferedReader(new FileReader("Computer Sc.txt")); String emp=inp1.readLine();

54 while(emp!=null) { System.out.println(emp); emp=inp1.readLine(); }

55 catch(FileNotFoundException e){ System.err.println("Error!"); System.exit(1); } catch(IOException e){ System.err.println("Error from reading file!"); }

56 Methods for BufferedReader readLine: read a line into a String read: read a char at a time close: close BufferedReader stream no methods to read numbers directly, so read numbers as Strings and then convert them (StringTokenizer later)

57 Reading Words in a String Using StringTokenizer Class There are BufferedReader methods to read a line and a character, but not just a single word StringTokenizer can be used to parse a line into words – import java.util.* – you can specify delimiters (the character or characters that separate words) the default delimiters are "white space" (space, tab, and newline)

58 import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; import java.util.StringTokenizer; //import java.io.File; public class ReadFile4 { public static void main(String[] args) { try{ BufferedReader inp1=new BufferedReader(new FileReader("Computer Sc.txt")); String emp=inp1.readLine();

59 while(emp!=null) { StringTokenizer wordFinder = new StringTokenizer(emp," "); while(wordFinder.hasMoreTokens()) { System.out.println(wordFinder.nextToken()); } //System.out.println(emp); emp=inp1.readLine(); }

60 catch(FileNotFoundException e){ System.err.println("Error!"); System.exit(1); } catch(IOException e){ System.err.println("Error from reading file!"); }

61 Example: StringTokenizer Display the words separated by any of the following characters: space, new line (\n), period (.) or comma (,). String inputLine = keyboard.nextLine(); StringTokenizer wordFinder = new StringTokenizer(inputLine, " \n.,"); //the second argument is a string of the 4 delimiters while(wordFinder.hasMoreTokens()) { System.out.println(wordFinder.nextToken()); } Question 2b or !tooBee Entering " Question,2b.or !tooBee. " gives this output:

62 Testing for End of File in a Text File When readLine tries to read beyond the end of a text file it returns the special value null – so you can test for null to stop processing a text file read returns -1 when it tries to read beyond the end of a text file

63 Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 63 Example: Using Null to Test for End-of-File in a Text File When using readLine test for null When using read test for -1

64 BufferedReader vs Scanner (parsing primitive types) Scanner – nextInt(), nextFloat(), … for parsing types BufferedReader – read(), readLine(), … none for parsing types –needs StringTokenizer then wrapper class methods like Integer.parseInt(token )

65 BufferedReader vs Scanner (Checking End of File/Stream (EOF)) BufferedReader – readLine() returns null – read() returns -1 Scanner – nextLine() throws exception –needs hasNextLine() to check first – nextInt(), hasNextInt(), …

66 BufferedReader inFile = … line = inFile.readline(); while (line != null) { // … line = inFile.readline(); } ------------------- Scanner inFile = … while (inFile.hasNextLine()) { line = infile.nextLine(); // … }

67 BufferedReader inFile = … line = inFile.readline(); while (line != null) { // … line = inFile.readline(); } ------------------- BufferedReader inFile = … while ((line = inFile.readline()) != null) { // … }

68 My suggestion Use Scanner with File – new Scanner(new File(“in.txt”)) Use hasNext…() to check for EOF – while (inFile.hasNext…()) Use next…() to read – inFile.next…() Simpler and you are familiar with methods for Scanner

69 My suggestion cont… File input – Scanner inFile = new Scanner(new File(“in.txt”)); File output – PrintWriter outFile = new PrintWriter(new File(“out.txt”)); – outFile.print(), println(), format(), close(), …

70 7. Reading Assignment- Opening Files with JFileChooser Class JFileChooser displays a dialog (known as the JFileChooser dialog) that enables the user to easily select files or directories.


Download ppt "Streams and File. 1. Introduction Data stored in variables and arrays is temporary For long-term retention of data, even after the programs that create."

Similar presentations


Ads by Google