SlideShare a Scribd company logo
www.webstackacademy.com
Java Programming Language SE – 6
Module 11: Console I/O and File I/O
www.webstackacademy.com
Objectives
● Read data from the console
● Write data to the console
● Describe files and file I/O
www.webstackacademy.com
Console I/O
● The variable System.out enables you to write to standard output.
System.out is an object of type PrintStream.
● The variable System.in enables you to read from standard input.
System.in is an object of type InputStream.
● The variable System.err enables you to write to standard error.
System.err is an object of type PrintStream.
www.webstackacademy.com
Writing to Standard Output
● The println methods print the argument and a newline character (n).
● The print methods print the argument without a newline character.
● The print and println methods are overloaded for most primitive types
(boolean, char, int, long, float, and double) and for char[], Object, and
String.
● The print(Object) and println(Object) methods call the toString method
on the argument.
www.webstackacademy.com
Reading From Standard
Input
public class KeyboardInput {
public static void main (String args[]) {
String s;
// Create a buffered reader to read
// each line from the keyboard.
InputStreamReader ir
= new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir);
System.out.println("Unix: Type ctrl-d to exit." +
"nWindows: Type ctrl-z to exit");
www.webstackacademy.com
Reading From Standard
Input
try {
// Read each input line and echo it to the screen.
s = in.readLine();
while ( s != null ) {
System.out.println("Read: " + s);
s = in.readLine();
}
// Close the buffered reader.
in.close();
} catch (IOException e) { // Catch any IO exceptions.
e.printStackTrace();
}}}
www.webstackacademy.com
Simple Formatted Output
● You can use the formatting functionality as follows:
out.printf(“name countn”);
String s = String.format(“%s %5d%n”, user, total);
● Common formatting codes are listed in this table.
www.webstackacademy.com
Simple Formatted Output
www.webstackacademy.com
Simple Formatted Input
The Scanner class provides a formatted input function.
A Scanner class can be used with console input streams as well as file or
network streams.
www.webstackacademy.com
Simple Formatted Input
You can read console input as follows:
import java.io.*;
import java.util.Scanner;
public class ScanTest {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
String param = s.next();
System.out.println("the param 1" + param);
int value = s.nextInt();
System.out.println("second param" + value);
s.close();
}}
www.webstackacademy.com
Files and File I/O
The java.io package enables you to do the following:
– Create File objects
– Manipulate File objects
– Read and write to file streams
www.webstackacademy.com
Creating a New File Object
The File class provides several utilities:
– File myFile;
– myFile = new File("myfile.txt");
– myFile = new File("MyDocs", "myfile.txt");
www.webstackacademy.com
Creating a New File Object
● Directories are treated like files in the Java programming
language. You can create a File object that represents a
directory and then use it to identify other files, for example:
File myDir = new File("MyDocs");
myFile = new File(myDir, "myfile.txt");
www.webstackacademy.com
The File Tests and Utilities
● File information:
– String getName()
– String getPath()
– String getAbsolutePath()
– String getParent()
– long lastModified()
– long length()
www.webstackacademy.com
The File Tests and Utilities
● File modification:
– boolean renameTo(File newName)
– boolean delete()
● Directory utilities:
– boolean mkdir()
– String[] list()
www.webstackacademy.com
The File Tests and Utilities
● File tests:
– Boolean exists()
– Boolean cabRead()
– Boolean canRead()
– Boolean isFile()
– Boolean isDirectory()
– Boolean isAbsolute();
– Boolean is Hidden();
www.webstackacademy.com
File Stream I/O
● For file input:
– Use the FileReader class to read characters.
– Use the BufferedReader class to use the readLine method.
● For file output:
– Use the FileWriter class to write characters.
– Use the PrintWriter class to use the print and println methods.
www.webstackacademy.com
File Input Example
public class ReadFile {
public static void main (String[] args) {
// Create file
File file = new File(args[0]);
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in
= new BufferedReader(new FileReader(file));
String s;
www.webstackacademy.com
Printing a File
s = in.readLine();
while ( s != null ) {
System.out.println("Read: " + s);
s = in.readLine();
}
// Close the buffered reader
in.close();
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
} catch (IOException e2) {
// Catch any other IO exceptions.
e2.printStackTrace();
}}}
www.webstackacademy.com
File Output Example
public class WriteFile {
public static void main (String[] args) {
// Create file
File file = new File(args[0]);
try {
// Create a buffered reader to read each line from standard in.
InputStreamReader isr
= new InputStreamReader(System.in);
BufferedReader in
= new BufferedReader(isr);
// Create a print writer on this file.
PrintWriter out
= new PrintWriter(new FileWriter(file));
String s;
www.webstackacademy.com
File Output Example
System.out.print("Enter file text. ");
System.out.println("[Type ctrl-d to stop.]");
// Read each input line and echo it to the screen.
while ((s = in.readLine()) != null) {
out.println(s);
}
// Close the buffered reader and the file print writer.
in.close();
out.close();
} catch (IOException e) {
// Catch any IO exceptions.
e.printStackTrace();
}}}
www.webstackacademy.com
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com

More Related Content

What's hot (20)

PPTX
Java file
sonnetdp
 
PDF
Java - File Input Output Concepts
Victer Paul
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PDF
C++ Files and Streams
Ahmed Farag
 
PPTX
Filehandling
Amandeep Kaur
 
PDF
Java IO
UTSAB NEUPANE
 
PPT
Byte stream classes.49
myrajendra
 
PPT
File Input & Output
PRN USM
 
PPTX
Handling I/O in Java
Hiranya Jayathilaka
 
PPT
Java stream
Arati Gadgil
 
PDF
I/O in java Part 1
ashishspace
 
PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
PPTX
Files io
Narayana Swamy
 
PPT
Java File I/O
Canterbury HS
 
PPS
Files & IO in Java
CIB Egypt
 
PPT
File handling
prateekgemini
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
File handling in vb.net
Everywhere
 
PPTX
Stream classes in C++
Shyam Gupta
 
PPTX
Java
Dhruv Sabalpara
 
Java file
sonnetdp
 
Java - File Input Output Concepts
Victer Paul
 
Understanding java streams
Shahjahan Samoon
 
C++ Files and Streams
Ahmed Farag
 
Filehandling
Amandeep Kaur
 
Java IO
UTSAB NEUPANE
 
Byte stream classes.49
myrajendra
 
File Input & Output
PRN USM
 
Handling I/O in Java
Hiranya Jayathilaka
 
Java stream
Arati Gadgil
 
I/O in java Part 1
ashishspace
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Files io
Narayana Swamy
 
Java File I/O
Canterbury HS
 
Files & IO in Java
CIB Egypt
 
File handling
prateekgemini
 
Java I/o streams
Hamid Ghorbani
 
File handling in vb.net
Everywhere
 
Stream classes in C++
Shyam Gupta
 

Similar to Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O (20)

PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PPTX
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
Input output files in java
Kavitha713564
 
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
PPTX
File Handling.pptx
PragatiSutar4
 
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
PPTX
ExtraFileIO.pptx
NguynThiThanhTho
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PPTX
IOStream.pptx
HindAlmisbahi
 
PPT
Basic input-output-v.1.1
BG Java EE Course
 
PDF
5java Io
Adil Jafri
 
PPTX
Io streams
Elizabeth alexander
 
PDF
JAVA 4.pdfdhfvksfvhsjfbjhdjhbjshjshjvcjdbh
KusumitaSahoo1
 
PPTX
Java Notes
Sreedhar Chowdam
 
PPTX
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
PPTX
Chapter 6
siragezeynu
 
PPTX
Java I/O
Jayant Dalvi
 
PPT
Java IO Streams V4
Sunil OS
 
PPTX
File Input and output.pptx
cherryreddygannu
 
File Handling in Java.pdf
SudhanshiBakre1
 
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Input output files in java
Kavitha713564
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
File Handling.pptx
PragatiSutar4
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Don Bosco BSIT
 
ExtraFileIO.pptx
NguynThiThanhTho
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
IOStream.pptx
HindAlmisbahi
 
Basic input-output-v.1.1
BG Java EE Course
 
5java Io
Adil Jafri
 
JAVA 4.pdfdhfvksfvhsjfbjhdjhbjshjshjvcjdbh
KusumitaSahoo1
 
Java Notes
Sreedhar Chowdam
 
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
Chapter 6
siragezeynu
 
Java I/O
Jayant Dalvi
 
Java IO Streams V4
Sunil OS
 
File Input and output.pptx
cherryreddygannu
 
Ad

More from WebStackAcademy (20)

PDF
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
PDF
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
PDF
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
PDF
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
PDF
Webstack Academy - Internship Kick Off
WebStackAcademy
 
PDF
Building Your Online Portfolio
WebStackAcademy
 
PDF
Front-End Developer's Career Roadmap
WebStackAcademy
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 

Core Java Programming Language (JSE) : Chapter XI - Console I/O and File I/O

  • 1. www.webstackacademy.com Java Programming Language SE – 6 Module 11: Console I/O and File I/O
  • 2. www.webstackacademy.com Objectives ● Read data from the console ● Write data to the console ● Describe files and file I/O
  • 3. www.webstackacademy.com Console I/O ● The variable System.out enables you to write to standard output. System.out is an object of type PrintStream. ● The variable System.in enables you to read from standard input. System.in is an object of type InputStream. ● The variable System.err enables you to write to standard error. System.err is an object of type PrintStream.
  • 4. www.webstackacademy.com Writing to Standard Output ● The println methods print the argument and a newline character (n). ● The print methods print the argument without a newline character. ● The print and println methods are overloaded for most primitive types (boolean, char, int, long, float, and double) and for char[], Object, and String. ● The print(Object) and println(Object) methods call the toString method on the argument.
  • 5. www.webstackacademy.com Reading From Standard Input public class KeyboardInput { public static void main (String args[]) { String s; // Create a buffered reader to read // each line from the keyboard. InputStreamReader ir = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(ir); System.out.println("Unix: Type ctrl-d to exit." + "nWindows: Type ctrl-z to exit");
  • 6. www.webstackacademy.com Reading From Standard Input try { // Read each input line and echo it to the screen. s = in.readLine(); while ( s != null ) { System.out.println("Read: " + s); s = in.readLine(); } // Close the buffered reader. in.close(); } catch (IOException e) { // Catch any IO exceptions. e.printStackTrace(); }}}
  • 7. www.webstackacademy.com Simple Formatted Output ● You can use the formatting functionality as follows: out.printf(“name countn”); String s = String.format(“%s %5d%n”, user, total); ● Common formatting codes are listed in this table.
  • 9. www.webstackacademy.com Simple Formatted Input The Scanner class provides a formatted input function. A Scanner class can be used with console input streams as well as file or network streams.
  • 10. www.webstackacademy.com Simple Formatted Input You can read console input as follows: import java.io.*; import java.util.Scanner; public class ScanTest { public static void main(String [] args) { Scanner s = new Scanner(System.in); String param = s.next(); System.out.println("the param 1" + param); int value = s.nextInt(); System.out.println("second param" + value); s.close(); }}
  • 11. www.webstackacademy.com Files and File I/O The java.io package enables you to do the following: – Create File objects – Manipulate File objects – Read and write to file streams
  • 12. www.webstackacademy.com Creating a New File Object The File class provides several utilities: – File myFile; – myFile = new File("myfile.txt"); – myFile = new File("MyDocs", "myfile.txt");
  • 13. www.webstackacademy.com Creating a New File Object ● Directories are treated like files in the Java programming language. You can create a File object that represents a directory and then use it to identify other files, for example: File myDir = new File("MyDocs"); myFile = new File(myDir, "myfile.txt");
  • 14. www.webstackacademy.com The File Tests and Utilities ● File information: – String getName() – String getPath() – String getAbsolutePath() – String getParent() – long lastModified() – long length()
  • 15. www.webstackacademy.com The File Tests and Utilities ● File modification: – boolean renameTo(File newName) – boolean delete() ● Directory utilities: – boolean mkdir() – String[] list()
  • 16. www.webstackacademy.com The File Tests and Utilities ● File tests: – Boolean exists() – Boolean cabRead() – Boolean canRead() – Boolean isFile() – Boolean isDirectory() – Boolean isAbsolute(); – Boolean is Hidden();
  • 17. www.webstackacademy.com File Stream I/O ● For file input: – Use the FileReader class to read characters. – Use the BufferedReader class to use the readLine method. ● For file output: – Use the FileWriter class to write characters. – Use the PrintWriter class to use the print and println methods.
  • 18. www.webstackacademy.com File Input Example public class ReadFile { public static void main (String[] args) { // Create file File file = new File(args[0]); try { // Create a buffered reader // to read each line from a file. BufferedReader in = new BufferedReader(new FileReader(file)); String s;
  • 19. www.webstackacademy.com Printing a File s = in.readLine(); while ( s != null ) { System.out.println("Read: " + s); s = in.readLine(); } // Close the buffered reader in.close(); } catch (FileNotFoundException e1) { // If this file does not exist System.err.println("File not found: " + file); } catch (IOException e2) { // Catch any other IO exceptions. e2.printStackTrace(); }}}
  • 20. www.webstackacademy.com File Output Example public class WriteFile { public static void main (String[] args) { // Create file File file = new File(args[0]); try { // Create a buffered reader to read each line from standard in. InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); // Create a print writer on this file. PrintWriter out = new PrintWriter(new FileWriter(file)); String s;
  • 21. www.webstackacademy.com File Output Example System.out.print("Enter file text. "); System.out.println("[Type ctrl-d to stop.]"); // Read each input line and echo it to the screen. while ((s = in.readLine()) != null) { out.println(s); } // Close the buffered reader and the file print writer. in.close(); out.close(); } catch (IOException e) { // Catch any IO exceptions. e.printStackTrace(); }}}
  • 22. www.webstackacademy.com Web Stack Academy (P) Ltd #83, Farah Towers, 1st floor,MG Road, Bangalore – 560001 M: +91-80-4128 9576 T: +91-98862 69112 E: [email protected]