Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Unit1_Java

The document provides an overview of Java threads, including their creation, advantages, and synchronization methods. It explains how to create threads by extending the Thread class or implementing the Runnable interface, as well as the concepts of parent and child threads. Additionally, it covers enumerations, wrapper classes, autoboxing, unboxing, annotations, and lambda expressions in Java.

Uploaded by

antonyraalph7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit1_Java

The document provides an overview of Java threads, including their creation, advantages, and synchronization methods. It explains how to create threads by extending the Thread class or implementing the Runnable interface, as well as the concepts of parent and child threads. Additionally, it covers enumerations, wrapper classes, autoboxing, unboxing, annotations, and lambda expressions in Java.

Uploaded by

antonyraalph7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

JAVA THREADS

• A thread in Java is the direction or path that is taken while a program is


being executed. Generally, all the programs have at least one thread,
known as the main thread.
• Threads are subprocesses with lightweight with the smallest unit of
processes and also has separate paths of execution.
• The main advantage of multiple threads is efficiency (allowing multiple
things at the same time). Another advantage is quick response.
• The Java Virtual Machine (JVM) allows an application to have multiple
threads of execution running concurrently.
• Multithreading is a technique that allows a processor to run multiple
threads at the same time, which can improve performance and
responsiveness
• Every thread has a priority. Threads with higher priority are executed in
preference to threads with lower priority.
Thread creation
There are two ways to create a thread:
1. By Extending Thread Class
2. By Implementing Runnable Interface
1. By Extending Thread Class - The simplest way to create a thread in Java is by extending
the Thread class and overriding its run() method. Thread class provide constructors and
methods to create and perform operations on a thread. The extending class must
override the run method and call the start method to begin execution of the thread.
Inside run, we will define the code that constitutes a new thread. The start() method of
the Thread class is used to start a newly created thread.
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
2. By Implementing Runnable Interface - If the class implements the Runnable
interface, the thread can be run by passing an instance of the class to a Thread
object's constructor and then calling the thread's start() method.
class Multi implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi m1=new Multi();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Thread Constructors and Methods
Constructors
Thread() - allocates a new Thread object.
Thread(Runnable target) - allocates a new Thread object
Thread(String name) - allocates a new Thread object.
Methods
currentThread() - returns a reference to the currently executing thread object.
getId() - returns the identifier of this Thread.
getName() - returns the thread's name.
getPriority() - returns the thread's priority.
getState() - returns the state of the thread.
isAlive() - tests if the thread is alive.
sleep() - Causes the currently executing thread to sleep for the specified
number of milliseconds.
start() - Causes the thread to begin execution.
yield() - Causes the currently executing thread object to temporarily
pause and allow other threads to execute.
run() - used to begin running the thread.
join() - a synchronization method that allows one thread to wait for
another thread to finish.
wait() - the calling thread stops its execution until notify() or notifyAll()
method is invoked by some other Thread.
Parent Thread and Child Threads
• In Java, the main thread is the parent thread, and the threads created
by the main thread are the child threads.
• The main thread is automatically created when a program runs and is
responsible for creating child threads. The main thread is the last
thread to finish executing and terminates the program.
• The threads created by the main thread are known as child threads.
• Any thread that is created by the main thread or another thread. A
child thread inherits certain properties from its parent thread but can
execute independently.
class A extends Thread { class ThreadDemo {
public void run() public static void main (String args[])
{ {
A obja = new A();
for (int i=0;i<=5;i++)
obja.start();
System.out.println("In thread A" +i); B objb=new B();
System.out.println("Exiting thread A"); objb.start();
}} }
class B extends Thread }
{ public void run()
{
for (int j=0;j<=5;j++)
System.out.println("In thread B" +j);
System.out.println("Exiting thread B");
} }
Synchronized Method
public class SimpleCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
SimpleCounter counter = new SimpleCounter();
Thread t1 = new Thread(() -> { for(int i = 0; i < 1000; i++) counter.increment(); });
Thread t2 = new Thread(() -> { for(int i = 0; i < 1000; i++) counter.increment(); });
t1.start();
count is a shared variable
t2.start();
increment() method is synchronized
t1.join(); Two threads try to increment 1000 times each
t2.join(); join() waits for both threads to complete
System.out.println("Total: " + counter.count); Ensures final count is always 2000
} }
Synchronized statement
public class SynchronizedBlockDemo {
private int count = 0;
private final Object lock = new Object(); // Dedicated lock object
public void incrementSafely() { // Synchronized block with more granular
locking
synchronized(lock) {
count++;
}
}

public static void main(String[] args) throws InterruptedException {


SynchronizedBlockDemo counter = new SynchronizedBlockDemo();
Thread t1 = new Thread(() -> { new Thread() creates a thread instance
for (int i = 0; i < 1000; i++) { () -> { } is a lambda expression defining
thread's task
counter.incrementSafely();
for loop runs 1000 times
} counter.incrementSafely() called in each
}); iteration
Thread t2 = new Thread(() -> { Thread will concurrently execute this 1000-
time increment
for (int i = 0; i < 1000; i++) {
Uses synchronized(lock) block
counter.incrementSafely();
Dedicated lock object prevents entire method
} being locked
}); Threads compete to enter synchronized block
t1.start(); Only one thread can access block at a time
Others wait until lock is released
t2.start();
Ensures count is incremented safely
t1.join();
t2.join();
System.out.println("Final Count: " + counter.count);
}
}
Enumerations
• An enumeration is a list of named constants that define a new data type
and its legal values.
• Enumerations are commonly used to define a set of values that
represent a collection of items.
• Example - We might use an enumeration to represent the error codes
that can result from some opeartion such as success, failed or pending.
• A Java enumeration defines a class type. It can have constructors,
methods and instance variables.
• It cannot be used to create objects.
• Unlike classes it neither inherit other classes nor can get extended.
• But it can implement interfaces.
Enums can be declared inside or outside a class.
Enums cannot be declared inside a method.
Syntax
accessmodifer enum enumname
{ constants }

Example:
public enum TypeName {
CONSTANT1,
CONSTANT2,
CONSTANT3,
// add more constants as needed
}
enum Level {
LOW, MEDIUM, HIGH
}
public class EnumLevel {
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
} } }
enum Day { // Define an enum for days of the week
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumDay {
public static void main(String[] args) {
for (Day day : Day.values()) { // Print all days of the week using the enum
System.out.println(day);
}
Day today = Day.MONDAY; // Accessing a specific enum constant
System.out.println("Today is: " + today);
} Enum Declaration: The Day enum is declared with the days of
} the week as its constants (SUNDAY, MONDAY, etc.).
Using Enum: In the main method, we iterate through all the
enum constants using Day.values() and print each day.
Accessing Specific Enum: We access a specific enum constant
(Day.MONDAY) and print it.
values() and valuesOf() methods
• values(): Returns an array of all the values defined in an enumeration
• valueOf(): Returns an enum constant by its name
enum Direction {
East, South, West, North
}
public class EnumDirection {
public static void main(String args[]) {
Direction dir;
Direction all[] = Direction.values(); // use values()
for (Direction a : all)
System.out.println(a);
System.out.println();
dir = Direction.valueOf("South"); // use valueOf()
System.out.println(“The current direction is” +dir);
} }
Enumerations are class types
enum fruits {
// Attributes associated to enum
Apple(120), Kiwi(60), Banana(20), Orange(80);
// internal data
private int price;
// Constructor
fruits(int pr) { price = pr; }
// Method
int getPrice() { return price; }
}
class Enumconstructor {
public static void main(String[] args)
{
System.out.println("All fruit prices : ");
// Iterating using enhanced for each loop
for (fruits f : fruits.values())
// Print and display the cost and perkg cost of fruits
System.out.println(f + " costs " + f.getPrice() + " rupees per kg.");
}
All fruit prices :
} Apple costs 120 rupees per kg.
Kiwi costs 60 rupees per kg.
Banana costs 20 rupees per kg.
Orange costs 80 rupees per kg.
Type Wrappers
• A Wrapper class in Java is a class whose object wraps or contains primitive
data types.
• Wrapper classes provide a way to use primitive data types (int, boolean,
etc..) as objects.
• In Java, sometimes we might need to use objects instead of primitive data
types. For example, while working with collections.
ArrayList<int> list = new ArrayList<>(); // error
ArrayList<Integer> list = new ArrayList<>(); // runs perfectly
We can store the null value in wrapper objects. For example,
int a = null; // error
Integer a = null; // runs perfectly
Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character
To create a wrapper object, use the wrapper class instead of the primitive type.
The following methods are used to get the value associated with the
corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(), booleanValue()

public class WrapperProgram {


public static void main(String[] args) {
Integer myInt = 10;
Double myDouble = 15.27;
Character myChar = 'C';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}
Autoboxing
• The automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing.
• For example – conversion of int to Integer, long to Long, double to
Double, etc.
• Autoboxing happens implicitly.
• We can assign a primitive directly to its wrapper class.
• Works seamlessly with method parameters.
• Particularly useful when working with collections that require
object types.
public class AutoboxingExample {
public static void main(String[] args) {
// Autoboxing: Primitive to Wrapper Class
int primitiveInt = 100; // Integer autoboxing
Integer wrappedInt = primitiveInt; // Automatic conversion from int to Integer
double primitiveDouble = 3.14; // Double autoboxing
Double wrappedDouble = primitiveDouble; // Automatic conversion from double to Double
boolean primitiveBoolean = true; // Boolean autoboxing
Boolean wrappedBoolean = primitiveBoolean; // Automatic conversion from boolean to Boolean
// Demonstrating autoboxing in method calls
printNumber(50); // Autoboxing int to Integer
// Autoboxing in collections
List<Integer> numbers = new ArrayList<>();
numbers.add(10); // Autoboxing int to Integer
numbers.add(20); // Autoboxing int to Integer }
public static void printNumber(Integer number) { // Method that accepts Integer object
System.out.println("Number: " + number);
} }
Unboxing
• Unboxing is the process of automatically converting a wrapper class
object back to its corresponding primitive data type.
• Unboxing is the reverse of boxing, which is the process of placing a
primitive variable in an object.
• Unboxing allows developers to extract primitive values from
wrapper classes without explicit conversions, making code more
readable and concise.
public class UnboxingExample {
public static void main(String[] args) {
// Wrapper to primitive conversion
Integer wrappedInt = Integer.valueOf(100);
int primitiveInt = wrappedInt; // Unboxing
// Unboxing in arithmetic operation
Integer a = 50;
Integer b = 30;
int sum = a + b; // Automatic unboxing
// Printing unboxed values
System.out.println("Primitive Int: " + primitiveInt);
System.out.println("Sum: " + sum);
processValue(50); // Unboxing in method call
}
// Method showing unboxing
public static void processValue(int value) {
System.out.println("Processed Value: " + value);
} }
Annotations
• An annotation is a tag representing metadata about classes,
interfaces, variables, methods, or fields.
• Annotations are used to provide supplemental information about a
program.
• Java Annotations provides information about the code.
• Annotations start with ‘@’.
• Annotations basically are used to provide additional information.
• Annotations do not change the action of a compiled program.
• Annotations help to associate metadata (information) to the program
elements i.e. instance variables, constructors, methods, classes, etc.
@Override annotation assures that the subclass method is overriding the
parent class method. If it is not so, compile time error occurs.
@Deprecated annoation marks that this method is deprecated so compiler
prints warning. It informs user that it may be removed in the future versions.
So, it is better not to use such methods.
@Retention - indicates how long annotations with the annotated type are to
be retained. Retention Policies: Determines whether the annotation is
available at compile time, runtime, or in the source code only.
RetentionPolicy.RUNTIME: Annotation available at runtime via reflection
RetentionPolicy.SOURCE: Annotation discarded by compiler
RetentionPolicy.CLASS: Annotation stored in .class file but not accessible at
runtime
@Inherited annotation is a meta-annotation (an annotation that can be
applied to other annotations) that affects how annotations are inherited by
subclasses.
class BaseClass {
public void display() {
System.out.println("In the base class,test() method");
}
}
class ChildClass extends BaseClass {
@Override
public void display() {
System.out.println("In the child class, test() method");
}
}
public class OverrideAnnotation {
public static void main(String args[]) {
System.out.println("@Override Example");
BaseClass obj = new ChildClass(); @Override Example
obj.display(); In the child class, test() method
}
}
Lambda Expressions

A lambda expression is a short block of code which takes in parameters


and returns a value. Lambda expressions are similar to methods, but
they do not need a name and they can be implemented right in the
body of a method.
Lambda expressions allow for cleaner and more efficient code,
especially in functional programming.
Syntax
The simplest lambda expression contains a single parameter and an
expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
• Lambda expressions in Java, introduced in Java SE 8, represent instances
of functional interfaces (interfaces with a single abstract method).
• a functional interface is an interface with exactly one abstract method
that can be used with lambda expressions.
• An interface with a single abstract method (SAM). The SAM is the
functional method for that interface.
• Functional interfaces in Java are the new feature that provides users
with the approach of fundamental programming.
• To indicate that an interface is a functional interface, you can use the
@FunctionalInterface annotation.
simple lambda expressions
class Test {
public static void main(String args[])
{
// Creating an ArrayList with elements {1, 2, 3, 4}
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// Using lambda expression to print all elements of arrL
arrL.forEach(n -> System.out.println(n));
// Using lambda expression to print even elements of arrL
arrL.forEach(n -> {
if (n % 2 == 0)
System.out.println(n);
});
}
}
Lambda expression with two arguments.

@FunctionalInterface
interface FuncInter1 {
int operation(int a, int b);
}
public class Test {
public static void main(String[] args) {
// Using lambda expressions to define the operations
FuncInter1 add = (a, b) -> a + b;
FuncInter1 multiply = (a, b) -> a * b;
// Using the operations
System.out.println(add.operation(6, 3)); // Output: 9
System.out.println(multiply.operation(4, 5)); // Output: 20
}
}
Block Lambda Expressions
• Java supports Expression Lambdas which contains blocks of code with more
than one statement. We call this type of Lambda Body a “Block Body“.
Lambdas that contain block bodies can be known as “Block Lambdas“.
• Block Lambda contains many operations that work on lambda expressions
as it allows the lambda body to have many statements.
• This includes variables, loops, conditional statements like if, else and switch
statements, nested blocks, etc. This is created by enclosing the block of
statements in lambda body within braces {}. This can even have a return
statement i.e return value.
Syntax:

(parameters) -> { lambda body }


interface Func {
int fact(int n);
}
class BlockLambdaProgram {
public static void main(String[] args)
{
// Block lambda expression
Func f = (n) ->
{
// Block body
int res = 1;
for (int i = 1; i <= n; i++)
res = i * res;
return res;
};
// Calling lambda function
System.out.println("Factorial of 5 : " + f.fact(5));
} }
Generic functional interfaces
• In Java, generic functional interfaces allow the declaration of similar
functions with different implementations.
• A lambda expression can't specify type parameters, so it's not generic.
However, a functional interface associated with lambda expression is
generic.

Syntax
interface SomeFunc {
T func(T t);
}
interface MyGeneric<T> {
T compute(T t);
}
public class LambdaGenericFuncI {
public static void main(String args[]) {
MyGeneric<String> reverse = (str) -> { // Lambda Expression
String result = "";
for(int i = str.length()-1; i >= 0; i--)
result += str.charAt(i);
return result;
};
MyGeneric<Integer> factorial = (Integer n) -> { // Lambda Expression
int result = 1;
for(int i=1; i <= n; i++)
result = i * result;
return result;
};
MyGeneric<Double> tax=(Double d) ->{
return tax*0.05;
};
System.out.println(reverse.compute("Generic Functional Interfaces"));
System.out.println(factorial.compute(7));
System.out.println(“Tax is:” +tax.compute(2353.56));
}
Passing Lambda expression as
arguments
• A lambda expression is an anonymous function that can be passed as
an argument to a method.
• In Java, we can pass a lambda expression as an argument to a method.
A lambda expression provides a clear and concise way to express
instances of functional interfaces.
• When we use a lambda expression to a method, the lambda
essentially implements the functional interface expected by the
method.
• A functional interface is an interface with only one abstract method.
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
public class LambdaExample {
// Method that accepts a MathOperation and performs the operation
public static int performOperation(int a, int b, MathOperation operation) {
return operation.operate(a, b);
}
public static void main(String[] args) {
// Passing a lambda expression to the method
int result = performOperation(5, 3, (a, b) -> a + b); // Lambda expression for addition
System.out.println("Addition Result: " + result);
result = performOperation(5, 3, (a, b) -> a - b); // Lambda expression for subtraction
System.out.println("Subtraction Result: " + result);
}
}
IO Basics
• Java I/O (Input and Output) is used to process the input and
produce the output.
• Java uses the concept of a stream to make I/O operation fast.
The java.io package contains all the classes required for input
and output operations.
• Streams: Streams represent a sequence of data. In Java, there
are two types of streams: input streams and output streams.
• Input streams are used to read data from a source, while output
streams are used to write data to a destination.
Byte Streams and Character Streams
• Character streams are useful in reading or writing text files which
are processed character by character.
• Java character streams are used to perform input and output for
16-bit unicode.
• Character stream is used to read and write a single character of
data.
• Using these we can read and write text data only.
• Byte streams are useful to read/write data from raw binary files.
• Java byte streams are used to perform input and output of 8-bit
bytes.
• Byte stream is used to read and write a single byte (8 bits) of data.
• Using these you can store characters, videos, audios, images etc.
Byte Stream classes
• ByteStream classes are used to read bytes from the input stream
and write bytes to the output stream.
• In other words, we can say that ByteStream classes read/write
the data of 8-bits.
• These classes are part of the java.io package.
• The ByteStream classes are divided into two types of classes, i.e.,
InputStream and OutputStream.
• The InputStream class provides methods to read bytes from a
file, console or memory.
• The OutputStream is used to write 8-bit bytes to the stream.
InputStream classes
• BufferedInputStream - This class provides methods to read bytes from
the buffer.
• DataInputStream - This class provides methods to read Java primitive
data types.
• FileInputStream - This class provides methods to read bytes from a
file.
OutputStream classes
• BufferedOutputStream - This class provides methods to write the
bytes to the buffer.
• DataOutputStream - This class provides methods to write the java
primitive data types.
• FileOutputStream - This class provides methods to write bytes to a
file.
Character Stream classes
• CharacterStream classes are used to work with 16-bit Unicode
characters. They can perform operations on characters, char arrays
and Strings.
• The CharacterStream classes are mainly used to read characters from
the source and write them to the destination.
• For this purpose, the CharacterStream classes are divided into two
types of classes, I.e., Reader class and Writer class.
• Reader class is used to read the 16-bit characters from the input
stream. All methods of the Reader class throw an IOException.
• Writer class is used to write 16-bit Unicode characters to the output
stream. The methods of the Writer class generate IOException.
Reader classes
• BufferedReader - This class provides methods to read characters from
the buffer.
• FileReader - This class provides methods to read characters from the
file.
• InputStreamReader - This class provides methods to convert bytes to
characters.
Writer classes
• BufferedWriter - This class provides methods to write characters to the
buffer.
• FileWriter - This class provides methods to write characters to the file.
• OutpuStreamWriter - This class provides methods to convert from bytes
to characters.
Predefined streams
• System class also contains three predefined stream variables, in, out, and
err.
• System.in refers to standard input, which is the keyboard by default.
Accessed through in which is used to read input from the keyboard.
• System.in is an object of type InputStream. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an
argument.
• System.in is a byte stream that has no character stream features.
• To obtain a character-based stream that is attached to the console, we
wrap System.in in a BufferedReader object.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
• System.out and System.err are objects of type PrintStream.
System.out refers to the standard output stream. By default, this is the
console. Accessed through out which is used to write output to the
display (console).
System.out.println("This is a regular message.");
• System.err refers to the standard error stream, which also is the console
by default. Accessed through err which is used to write error output to
the display (console).
System.err.println("This is an error message.");
Reading Console Input
The constructor for BufferedReader is:
BufferedReader(Reader in, Charset cs)

• This constructor creates a BufferedReader that reads from a specified


Reader (like FileReader, InputStreamReader, etc.) using a specific
Charset for encoding.
• System.console().charset() is used to retrieve the default charset of
the console.
Example:
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in, System.console().charset()));
Reading Characters
import java.io.*;
class ReadChar {
public static void main(String[] args) throws IOException{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in,
System.console().charset()));
System.out.println("Enter Character, 'q' to quit");
do{
c=(char)br.read();
System.out.println(c);
}while(c!='q');
}
}
Reading console input
• In Java, there are different ways to read input from the user in the command line
environment(console).
1. Using Buffered Reader Class
BufferedReader reader = new BufferedReader( new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
2. Using Scanner Class
Scanner in = new Scanner(System.in);
String name = in.nextLine();
3. Using Console Class
String name = System.console().readLine();
System.out.println("You entered string " + name);
Reading Strings
import java.io.*;
class ReadString {
public static void main(String[] args) throws IOException{
String s;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in,System.console().charset()));
System.out.println("Enter string, 'stop' to quit");
do{
s=br.readLine();
System.out.println(s);
}while(!s.equals("stop"));
}
}
Buffered Reader Class - BufferedReader class is used to read the text from
a character-based input stream. It can be used to read data line by line by
readLine() method.
Scanner class is used to get user input, and it is found in the java.util
package. To use the Scanner class, create an object of the class and use
any of the available methods found in the Scanner class documentation.
In our example, we will use the nextLine() method, which is used to read
Strings.
Console class - It is used to read from and write to the console. A Console
object is obtained by calling System.console().
Writing Console Output
• The PrintStream is a bult-in class that provides two methods print()
and println() to write console output.
• The print() method writes console output in the same line. The
println() method writes console output in a separete line (new line).
• Alternatively, the PrintStream class provides a method write() to write
console output.
• The write() method take integer as argument, and writes its ASCII
equalent character on to the console.
class WriteDemo {
public static void main(String[] args) {
int a=65;
int b=97;
int c=35;
System.out.write(a);
System.out.write(b);
System.out.write(c);
System.out.write('\n');
}
}

Output:
Aa#
PrintWriter Class
• The PrintWriter class of the java.io package can be used to write
output data in a commonly readable form (text).
• PrintWriter converts the primitive data(int, float, char, etc.) into the
text format. It then writes that formatted data to the writer.
Constructor
PrintWriter(OutputStream outputstream, boolean flushingOn)
Example
PrintWriter pw=new PrintWriter(System.out, true);
If flushingOn is true, flushing automatically takes place. If false, flushing
is not automatic.
public class PrintWriterExample {
public static void main(String[] args) {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out, true);
writer.write("writing the data on a console");
writer.close();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
try {
writer1 = new PrintWriter(new File("D:\\testout.txt"));
writer1.write("writing the data in a text file testout.txt ");
} catch (FileNotFoundException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally { // Close the writer if it was initialized
if (writer1 != null) {
writer1.close();
}
}}}
Reading and Writing Files
• Java provides a number of classes and meyhods that allow you to
read and write files.
• Two of the most often used stream classes are FileInputStream and
FileOutputStream which create byte streams linked to files.
• To open a file, you simply create an object of these classes, specifying
the name of the file as an argument to the constructor.
Constructors
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
fileName specifies the name of the file that you want to open. When
you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
• When you are done with a file, you must close it. This is done by the
close() method.
void close() throws IOException
• Closing a file releases the system resources allocated to the file, allowing
them to be used by another file.
• To read from a file, you can use a version of read() that is defined within
FileInputStream.
int read() throws IOException
• Each time that is called,it reads a single byte from the file and returns
the byte as an integer value read() returns -1 when an attempt to read at
the end of the stream. It can throw an IOException.
import java.io.*;
public class FileReadWrite
{
public static void main(String[] args) {
try { // Write to a file
FileWriter writer = new FileWriter("c:\\test.txt");
writer.write("Hello! This is a test file.\n");
writer.write("This is the second line.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing the file.");
e.printStackTrace();
}
// Read from the file
try {
FileReader reader = new FileReader("c:\\test.txt");
int character;
System.out.println("\nContent of the file:");
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace(); Successfully wrote to the file.
}
Content of the file:
} Hello! This is a test file.
} This is the second line.

You might also like