File Handlingb in java. A brief presentation on file handling
abdulsamadbrohi461
99 views
66 slides
May 14, 2024
Slide 1 of 66
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
About This Presentation
File handling in Java
Size: 1.79 MB
Language: en
Added: May 14, 2024
Slides: 66 pages
Slide Content
File Handling in Java
Table of contents 01 02 File File Handling 03 Streams 04 File Class 05 File Reading 06 File Writing
File 01 What is a File?
What is a File? text, images, videos, programs, and more Types of Files Content Attributes size, type, creation date, modification date, permissions, etc. text files, binary files, executable files, configuration files, etc Named collection of related information stored on a storage medium, typically a disk </>
File Handling 02
What is File Handling? Managing files in a computer system. Involves reading, writing, creating, deleting, and modifying files. Accessing files for read/write Writing Opening Reading Retrieving data from files Storing data into files Closing Ending file access
Streams 03
What are Streams? Represent a sequence of data elements from a source I/O Channels, Arrays, ArrayLists , etc. Do not store data; they are pipelines through which data flows. Java views files as sequential streams of bytes. End of a file is determined by EOF (End-of-File) marker. File streams can handle data as bytes characters File Streams
Byte-Based and Character-Based Streams File streams can handle data as bytes or characters Character Streams File Streams Byte Steams deal with binary data used for binary files value 5 stored in binary format of the numeric value 5, e.g., 0000101 handle data as a sequence of characters used for text files value 5 stored in binary format of the character value 5, e.g., 00000000 00110101, represents Unicode of ‘5’
Examples of File Streams Some Examples (Classes) are Character Streams Byte Streams FileInputStream FileOutputStream FileReader FileWriter BufferedReader BufferedWriter
Standard Streams Java programs associate streams with devices. Actually, an object of standard streams is created and associated with devices enables a program to input bytes from the keyboard System.out (standard output stream) System.in (standard input stream) enables a program to output character data to the screen System.err (standard error stream) enables a program to output character-based error messages to the screen
File Class 04
The File Class An abstract representation of file and directory pathnames Part of the java.io package Allows operations such as obtaining properties renaming deleting creating directories or files Provides certain methods for performing operations, like .delete() , . createNewFile () , . getName ()
Pathnames pathname strings used to name files and directories. First name in an abstract pathname is a directory name. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file e.g., C:\Users\Hassan\Documents\file.txt Pathname is either absolute or relative
Relative Pathname A relative pathname specifies the path relative to the current working directory. e.g., pathname is ‘file.txt’ We’re are working in C:\Users\Username\Documents file.txt is the relative path to our directory Absolute Pathname An absolute pathname specifies the full path starting from the root directory. e.g., ‘C:\Users\Username\Documents\file.txt’
File Class Methods Name Return Type Description File(pathname: String) File Creates a File object for the specified path name. The path name may be a directory or a file. canRead () Boolean Returns true if the file exists and can be read. createNewFile () Boolean Creates a new empty file. canWrite () Boolean Returns true if the file exists and can be written. exists() Boolean Returns true if the file or the directory exists. delete() Boolean Deletes the file. getName () String Returns the last name of the complete directory and file name. getAbsolutePath () String Returns the complete absolute file or directory name length() Long Returns the size of the file, or 0 if it does not exist or if it is a directory.
File Class Methods Name Return Type Description isDirectory () boolean Returns true if the File object represents a directory. isFile() boolean Returns true if the File object represents a file. isAbsolute() boolean Returns true if the File object is created using an absolute path name. isHidden () boolean Returns true if the file represented in the File object is hidden. lastModified () long Returns the time that the file was last modified. renameTo ( dest : File) boolean Renames the file or directory represented by this File object to the specified name represented in dest . The method returns true if the operation succeeds. list() String[] Retrieves an array of files available in the directory. mkdir () Boolean Creates a new directory.
Code Examples
Code: import java . io . File ; public class FileClass { public static void main ( String [] args ) { // Create a File object File file = new File ( "D: \\ Other Data \\ Seasons.txt" ); // Check if is a file System . out . println ( " Is it a file? : " + file . isFile ()); // Check if file can be read and written System . out . println ( "Can read file: " + file . canRead ()); System . out . println ( "Can write to file: " + file . canWrite ()); // Check if file exists System . out . println ( "File exists: " + file . exists ()); // Get file name and absolute path System . out . println ( "File name: " + file . getName ()); System . out . println ( "Absolute path: " + file . getAbsolutePath ()); } }
Output:
Code: import java . io . File ; public class FileClass { public static void main ( String [] args ) { // Create a File object File file = new File ( "D: \\ Other Data \\ Seasons.txt" ); // Get file length System . out . println ( "File length (in bytes): " + file . length ()); // Check if it's a directory and if it's an absolute path System . out . println ( "Is directory: " + file . isDirectory ()); System . out . println ( "Is absolute path: " + file . isAbsolute ()); // Get file path, last modified time, and rename the file System . out . println ( "File path: " + file . getPath ()); System . out . println ( "Last modified: " + file . lastModified ()); } }
Output:
Rename and Delete: import java . io . File ; public class FileClass { public static void main ( String [] args ) { File file = new File ( "D: \\ Other Data \\ Seasons.txt" ); // rename the file String newName = "Unwatched Seasons.txt" ; File newFile = new File ( file . getParent (), newName ); if ( file . renameTo ( newFile )) { System . out . println ( "File renamed successfully." ); } else { System . out . println ( "Failed to rename the file." ); } // Deleting the file if ( file . delete ()) { System . out . println ( "File deleted successfully." ); } else { System . out . println ( "Failed to delete the file." ); } } }
Output:
Create a File: import java . io . File ; import java . io . IOException ; public class FileClass { public static void main ( String [] args ) { File file = new File ( "D: \\ Other Data \\ Seasons.txt" ); try { // Creating a new file if ( file . createNewFile ()) { System . out . println ( "File created successfully at: " + file . getAbsolutePath ()); } else { System . out . println ( "File already exists." ); } } catch ( IOException e ) { System . out . println ( "An error occurred while creating the file." ); e . printStackTrace (); } } }
Output:
File Reading 05
What is File Reading? Process of retrieving data stored in a file on a storage device and bringing that data into your program's memory for further processing or manipulation. Reading from a file involves: Open File: Specify file path and permissions. Access Content: Read Line by Line (for text files). Read Blocks or Chunks (for larger files). Read All at Once (for smaller files). Process Data: Manipulate or analyze the read data. Close File: Release system resources
Classes for File Reading Some Examples (Classes) are Character Streams Byte Streams FileInputStream FileReader BufferedReader Scanner
FileReader int letters ; FileReader reader = null ; try { reader = new FileReader ( " fileName " )) // .ready() tells whether the stream is ready to read while ( reader . ready ()) { // .read() reads characters and stores as Unicode values letters = reader . read (); System . out . print (( char ) letters ); } } catch ( IOException e ) { System . out . println ( e . toString ());; } finally { reader . close (); } Import from java.io package, before using
Output:
Limitations of FileInputStream Primarily for reading bytes, lacking higher-level functionalities. Doesn't handle character encoding automatically Must be used with InputStreamReader class and Character-set must be specified. No built-in method for reading lines of text Absence of direct EOF (end-of-file) checking methods Limitations of FileReader Slower performance when reading larger files due to character-by-character reading Requires additional handling for reading lines by combining with other classes.
BufferedReader Reads data from a character-input stream efficiently by buffering characters, reducing the number of I/O operations and improving performance. Provides readLine () , for reading lines of text from an input stream, returning null when the end of the stream is reached. Limitations: Lacks built-in methods for directly reading specific data types; manual parsing is needed. Primarily designed for reading text; not optimized for reading binary data.
Code: BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( "D: \\ Seasons.txt" )) String line ; while (( line = reader . readLine ()) != null ) { System . out . println ( line ); } } catch ( IOException e ) { e . printStackTrace (); } finally { reader . close (); } First import it before using from java.io package
Output:
Scanner Provides a simple way to read and parse primitive types and strings from various input sources like files, streams, or strings. Has methods like nextInt () , nextDouble () , nextLine () , etc., to read integers, doubles, strings, etc., from the input source Import Scanner from java.util package before using Limitations: For large files or complex parsing requirements, Scanner might not be as efficient as BufferedReader Might throw exceptions if the input doesn't match the expected data type, requiring additional error handling
Reading Integer: int number ; Scanner input = null ; try { input = new Scanner ( new File ( "D: \\ Numbers.txt" )); // . hasNextInt () tells whether next is integer while ( input . hasNextInt ()) { number = input . nextInt (); System . out . println ( number ); } } catch ( FileNotFoundException e ) { System . out . println ( e . toString ());; } finally { input . close (); }
Output:
Reading Double: double number1 ; Scanner input = null ; try { input = new Scanner ( new File ( "D: \\ doubleNumbers.txt" )); while ( input . hasNextDouble ()) { number1 = input . nextDouble (); System . out . println ( number1 ); } } catch ( FileNotFoundException e ) { System . out . println ( e . toString ());; } } finally { input . close (); }
Output:
Reading Line: String line ; Scanner input = null ; try { input = new Scanner ( new File ( "D: \\ Seasons.txt" )); while ( input . hasNextLine ()) { line = input . nextLine (); System . out . println ( line ); } } catch ( FileNotFoundException e ) { System . out . println ( e . toString ());; } finally { input . close (); }
Output:
File Writing 06
What is File Writing? Process of creating, opening, and manipulating files to save data or information onto a storage device. Allows to make data available even after the program finishes. Writing to a file involves: Open File: Specify file path and permissions, e.g., File class. Access Content: Read Line by Line, Blocks or Chunks, All at Once. Process Data: Manipulate or analyze the read data. Write Data: Write data using classes. Close File: Release system resources
Classes for File Reading Some Examples (Classes) are Character Streams Byte Streams FileOutputStream FileWriter BufferedWriter PrintWriter
File Writer Powerful tool for writing character-based data to files Designed to work with text files containing letters, punctuation, and other standard characters. Offers methods like write, write(char ch ) , write(char[] charArr ), write(String str) , to write characters, arrays of characters, strings. Uses an internal buffer to store data efficiently before writing it to the file. One can flush the buffer manually using flush() to ensure data is written immediately Import FileWriter from java.io package before using
Limitations of FileOutputStream Used for writing raw bytes of data to a file. Doesn't provide methods for handling textual data directly. Doesn't buffer data, which leads to frequent disk writes, impacting performance with small writes Limitations of FileWriter Used for writing characters, strings, char arrays to a file Not optimized for handling large amounts of data efficiently
Writing Line/String: String content = "Some content to write into file." ; FileWriter writer = null ; try { writer = new FileWriter ( "output.txt" ); writer . write ( content ); writer . flush (); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing." ); e . printStackTrace (); } finally { writer . close (); }
Output:
Writing Characters String content = "Writing Characters to File" ; FileWriter writer = null ; try { writer = new FileWriter ( "output1.txt" ); for ( int i = ; i < content . length (); i ++){ writer . write ( content . charAt ( i )); } System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." ); e . printStackTrace (); } finally { writer . close (); }
Output:
Writing Character Array FileWriter writer = null ; try { char [] charArray = { 'J' , 'a' , 'v' , 'a' , '-' , '2' , '1' }; writer = new FileWriter ( "output2.txt" ); writer . write ( charArray ); writer . flush (); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." + " \n " + e . toString ()); } finally { writer . close (); }
Output:
Buffered Writer Powerful tool for writing text to files more efficiently than the basic FileWriter . Works by buffering data in memory before writing it to the underlying file stream. This can significantly improve performance, especially when dealing with small files or frequent writes. Offers methods like write, write(char ch ) , write(char[] charArr ), write(String str) , to write characters, arrays of characters, strings. One can flush the buffer manually using flush() to ensure data is written immediately Import BufferedWriter from java.io package before using
Writing String/ Lines: String data = "Writing using buffered Writer" ; BufferedWriter writer = null ; try { writer = new BufferedWriter ( new FileWriter ( "myfile.txt" )); writer . write ( data ); writer . flush (); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." + " \n " + e . toString ()); } finally { writer . close (); }
Output:
Same syntax and procedure as that of FileWriter . Use these write(char ch ) , write(char[] charArr ). Writing Character and Char Array: When to use BufferedWriter ? Consider using BufferedWriter whenever you need to: Write large amounts of character data to files. Improve the performance of file writes, especially for small files or frequent writes. Enhance the stability and reliability of your file handling
PrintWriter Writes formatted text to a file or any output stream. Part of the java.io package. Handles automatic buffering and flushing, providing smoother and more efficient output. Provides simple methods like print() , println () , and printf () for various data types, streamlining text output. Allows specifying the character encoding (e.g., UTF-8) for consistent handling of different language characters. Uses format specifiers ( %d , %s , etc.) to format data before writing, allowing for custom output formats
Using print()/ println (): PrintWriter writer = null ; try { writer = new PrintWriter ( "output.txt" ); writer . println ( "This is PrintWriter on Java, ver :" + 21 ); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." + " \n " + e . toString ()); } finally { writer . close (); } .print() writes the data to the file as it is . println () adds newline after writing
Output:
Formatted Writing: int age = 20 ; String name = "Hassan" ; PrintWriter writer = null ; try { writer = new PrintWriter ( "output1.txt" ); writer . printf ( "Name: %s, Age: %d \n " , name , age ); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." + " \n " + e . toString ()); } finally { writer . close (); } Can be achieved by printf () Custom formatting is passed as argument to method Format specifiers are also used.
Output:
try-with-resources Introduced in Java 7 that simplifies resource management. Ensures resources are automatically closed regardless of whether your code completes normally or throws an exception. Working and Usage Within the parentheses after try , you can create resource variables representing objects that need to be closed. The code block in try, can use the declared resources like any other variable. Once the block exits, regardless of the reason (normal execution or exception), all resources are automatically closed in the reverse order of their declaration.
Syntax: try ( ResourceType1 resource1 = /* initialization */ ; ResourceType2 resource2 = /* initialization */ ; // ... add more resources as needed ResourceTypeN resourceN = /* initialization */ ) { // Your code that uses the resources declared above } catch ( Exception1 exception1 ) { // Handle exception1 thrown by your code or resources } catch ( ExceptionN exceptionN ) { // ….Handle exceptionN thrown by your code or resources }
Example Code: int age = 20 ; String name = "Hassan" ; try ( PrintWriter writer = new PrintWriter ( "output.txt" )){ writer . printf ( "Name: %s, Age: %d \n " , name , age ); System . out . println ( "Content has been written to the file." ); } catch ( IOException e ) { System . out . println ( "An error occurred while writing to the file." + " \n " + e . toString ()); } Formatted writing code realized using try-with-resources