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
5java Io
Adil Jafri
 
PPTX
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
PPTX
Input output files in java
Kavitha713564
 
PPS
Java session08
Niit Care
 
PPT
Introduction to objects and inputoutput
Ahmad Idrees
 
PPTX
Java I/O
Jayant Dalvi
 
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
PDF
Basic i/o & file handling in java
JayasankarPR2
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PPT
07-Basic-Input-Output.ppt
Ajenkris Kungkung
 
DOCX
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
PPTX
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PDF
Java Day-6
People Strategists
 
PPTX
IOStream.pptx
HindAlmisbahi
 
PPTX
ExtraFileIO.pptx
NguynThiThanhTho
 
PPTX
I/O Streams
Ravi Chythanya
 
PPTX
Io streams
Elizabeth alexander
 
5java Io
Adil Jafri
 
JAVA (UNIT 3)
Dr. SURBHI SAROHA
 
Input output files in java
Kavitha713564
 
Java session08
Niit Care
 
Introduction to objects and inputoutput
Ahmad Idrees
 
Java I/O
Jayant Dalvi
 
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Basic i/o & file handling in java
JayasankarPR2
 
File Handling in Java.pdf
SudhanshiBakre1
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
07-Basic-Input-Output.ppt
Ajenkris Kungkung
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
File Input and output.pptx
cherryreddygannu
 
Java Day-6
People Strategists
 
IOStream.pptx
HindAlmisbahi
 
ExtraFileIO.pptx
NguynThiThanhTho
 
I/O Streams
Ravi Chythanya
 
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)

PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Digital Circuits, important subject in CS
contactparinay1
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

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]