0% found this document useful (0 votes)
13 views77 pages

AWT and Swings

Uploaded by

Abinet Bizuayehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views77 pages

AWT and Swings

Uploaded by

Abinet Bizuayehu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

AWT and Swings

• Java is equipped with many powerful, yet


easy-to-use graphical user interface (GUI)
components, such as the input and output
dialog boxes.
• You can use these to make your programs
attractive and user-friendly

1
Using Dialog Boxes for Input/output
• Recall that you have already used the class
Scanner to input data into a program from the
keyboard, and you used the object System.out to
output the results to the screen
• Another way to gather input and output results is
to use a graphical user interface (GUI).
• Java provides the class JOptionPane, which allows
the programmer to use GUI components for I/O.

2
Continued…
• The class JOptionPane is contained in the
package javax.swing.
• The two methods of this class that we use are:
showInputDialog and showMessageDialog.
• The method showInputDialog allows the user
to input a string from the keyboard; the method
showMessageDialog allows the programmer to
display the results.

3
Continued…
• The syntax to use the method showInputDialog is:

• where str is a String variable and stringExpression


is an expression evaluating to a string.
• When this statement executes, a dialog box
containing stringExpression appears on the screen
prompting the user to enter the data.

4
Continued…
• Consider the following statement (suppose that
name is a String variable):
– name = JOptionPane.showInputDialog("Enter your
name and press OK");
• When this statement executes, the dialog box
shown in figure below appears on the screen.

5
Continued…
• After you enter a name and click the OK
button (or press the Enter key), the dialog box
disappears and the entered name is assigned
to the variable name.

6
Continued…

7
Continued…
• Table below describes the options of the class
JOptionPane that can be used with the
parameter messageType. The option name is
shown in bold.

8
Continued…
• JOptionPane.showMessageDialog(null, "Hello
World!", "Greetings",
JOptionPane.INFORMATION_MESSAGE); is
shown in Figure below.

9
Continued…
• The class JOptionPane is contained in the
package javax.swing. Therefore, to use this
class in a program, the program must import it
from the package javax.swing.
• The following statements illustrate how to
import the class JOptionPane (you can use
either format):
• import javax.swing.JOptionPane; or
• import javax.swing.*;
10
Continued…
• The above program uses input and output
dialog boxes to accomplish its job.
• When you run this program, you see only one
dialog box at a time.
• However, suppose that you want the program
to display all the input and output in one
dialog box, as shown below Figure 1-8

11
Sample GUI

12
Continued…
• In Java terminology, such a dialog box is called a
graphical user interface (GUI), or simply a user
interface.
• In this GUI, the user enters the length and width in
the top two white boxes.
• When the user clicks the Calculate button, the
program displays the area and the perimeter in
their respective locations.
• When the user clicks the Exit button, the program
terminates.
13
Continued…
• In this interface, the user can:
– See the entire input and output simultaneously
– Input values for length and width, in any order of
preference
– Input values that can be corrected after entering
them and before clicking the Calculate button
– Enter another set of input values and click the
Calculate button to obtain the area and perimeter
of another rectangle

14
Continued…
• The interface shown in figure below contains
various Java GUI components that are labeled.

15
Continued…
• Creating this type of user interface is not
difficult.
• Java has done all the work; you merely need
to learn how to use the tools provided by Java
to create such an interface

16
GUI Components
• We will discuss the following GUI components
– Windows
– Labels
– Text fields
– Buttons
• GUI components, such as labels, are placed in
an area called the content pane of the window

17
Creating a Window
• GUI components such as windows and labels are, in
fact, objects.
• Recall that an object is an instance of a particular class.
• Therefore, these components (objects) are instances
of a particular class type.
• JFrame is a class and the GUI component window can
be created by using a JFrame object.
• Various attributes are associated with a window. For
example:
– Every window has a title.
– Every window has width and height
18
JFrame
• The class JFrame provides various methods to
control the attributes of a window.
• For example, it has methods to set the window
title and methods to specify the height and
width of the window.
• For example:
– JFrame myWindow = new JFrame();
– JFrame myWindow = new JFrame(“Square”);
– myWindow.setSize(400,300);
– myWindow.setVisible(true); 19
Continued…

20
Continued…
• The program to create the window shown
above we use the class JFrame; this class is
contained in the package javax.swing.
• Therefore, the program must include either of
the following two statements:
• import javax.swing.*; or:
• import javax.swing.JFrame;

21
Sample Code to create a Frame
• //Java program to create a window.
• import javax.swing.*;
• public class RectangleProgramOne extends JFrame {
• private static final int WIDTH = 400;
• private static final int HEIGHT = 300;
• public RectangleProgramOne() {
• setTitle("Area and Perimeter of a Rectangle");
• setSize(WIDTH, HEIGHT);
• setDefaultCloseOperation(EXIT_ON_CLOSE);
• setVisible(true);
• }
• public static void main(String[] args) {
• RectangleProgramOne rectProg = new RectangleProgramOne();
• }
• }
22
Getting Access to the Content Pane
• If you can visualize JFrame as a window, think of
the content pane as the inner area of the window
(below the title bar and inside the border).
• The class JFrame has the method getContentPane
that you can use to access the content pane of
the window.
• However, the class JFrame does not have the
necessary tools to manage the components of
the content pane

23
Continued…
• The components of the content pane are
managed by declaring a reference variable of
the Container type and then using the method
getContentPane, as shown next.
• Consider the following statements:
– Container pane;
– pane = getContentPane(); or
• Container pane = getContentPane();

24
Continued…
• To add components such as labels and text
fields to the content pane, you use the
method add of the class Container, which is
also described in Table 6-2.

25
Continued…
• The class Container is contained in the package
java.awt.
• To use this class in your program, you need to
include one of the following statements:
– import java.awt.*; or:
– import java.awt.Container;
• Consider the following statement:
– pane.setLayout(new GridLayout(5, 2));

26
Continued…
• //Java program to create a window and place four labels
• import javax.swing.*;
• import java.awt.*;
• public class RectangleProgramTwo extends JFrame {
• private static final int WIDTH = 400;
• private static final int HEIGHT = 300;
• private JLabel lengthL, widthL, areaL, perimeterL;
• public RectangleProgramTwo() {
• setTitle("Area and Perimeter of a Rectangle");
• lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
• widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
• areaL = new JLabel("Area: ", SwingConstants.RIGHT);
• perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
• Container pane = getContentPane();
• pane.setLayout(new GridLayout(4, 1));
• pane.add(lengthL);
• pane.add(widthL);
• pane.add(areaL);
• pane.add(perimeterL);
• setSize(WIDTH, HEIGHT);
• setVisible(true);
• setDefaultCloseOperation(EXIT_ON_CLOSE);
• }
• public static void main(String[] args) {
• RectangleProgramTwo rectObject = new RectangleProgramTwo(); 27
JTextField
• Text fields are objects belonging to the class
JTextField.
• Therefore, you can create a text field by
declaring a reference variable of type JTextField
followed by an instantiation of the object.

28
Continued…

29
Continued…
• Consider the following statements:
– private JTextField lengthTF, widthTF, areaTF,
– perimeterTF; //Line 1
– lengthTF = new JTextField(10); //Line 2
– widthTF = new JTextField(10); //Line 3
– areaTF = new JTextField(10); //Line 4
– perimeterTF = new JTextField(10); //Line 5

30
Continued…
• The following statements add these
components to the container:
– pane.add(lengthTF);
– pane.add(widthTF);
– pane.add(areaTF);
– pane.add(perimeterTF);

31
Sample code
• //Java program to create a window
• //and place four labels and four text fields
• import javax.swing.*;
• import java.awt.*;
• public class RectangleProgramThree extends JFrame {
• private static final int WIDTH = 400;
• private static final int HEIGHT = 300;
• private JLabel lengthL, widthL, areaL, perimeterL;
• private JTextField lengthTF, widthTF, areaTF,
• perimeterTF;
• public RectangleProgramThree() {
• setTitle("Area and Perimeter of a Rectangle");
• lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
• widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
• areaL = new JLabel("Area: ", SwingConstants.RIGHT);
• perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
• lengthTF = new JTextField(10);
• widthTF = new JTextField(10);
• areaTF = new JTextField(10);
32
• perimeterTF = new JTextField(10);
Continued…
• Container pane = getContentPane();
• pane.setLayout(new GridLayout(4, 2));
• pane.add(lengthL);
• pane.add(lengthTF);
• pane.add(widthL);
• pane.add(widthTF);
• pane.add(areaL);
• pane.add(areaTF);
• pane.add(perimeterL);
• pane.add(perimeterTF);
• setSize(WIDTH, HEIGHT);
• setVisible(true);
• setDefaultCloseOperation(EXIT_ON_CLOSE);
• }
• public static void main(String[] args) {
• RectangleProgramThree rectObject = new RectangleProgramThree();
• }} 33
JButton
• To create a button, Java provides the class
JButton.
• Thus, to create objects belonging to the class
JButton, we use a technique similar to the one
we used to create instances of JLabel and
JTextField. Table 6-5 shows some methods of
the class JButton.

34
Continued…

35
Continued…
• The following three lines will create two
buttons, Calculate and Exit, shown in earlier
GUI
– JButton calculateB, exitB; //Line 1
– calculateB = new JButton("Calculate"); //Line 2
– exitB = new JButton("Exit"); //Line 3

36
HANDLING AN EVENT
• Clicking a JButton creates an event, known as
an action event, which sends a message to
another object, known as an action listener.
• When the listener receives the message, it
performs some action.
• Sending a message or an event to a listener
object simply means that some method in the
listener object is invoked with the event as the
argument.
37
Continued...
– listeners are objects interested in events
– sources are objects that “fire” events
– register listeners with sources
• component.add<EventType>Listener
– EventTypes are ActionEvent, AdjustmentEvent, ComponentEvent,
FocusEvent, ItemEvent, KeyEvent, MouseEvent, TextEvent, WindowEvent
– implement methods of listener interfaces in listener
classes
• an event object is passed to the methods
• ActionListener, AdjustmentListener, ComponentListener,
FocusListener, ItemListener, KeyListener, MouseListener,
MouseMotionListener, TextListener, WindowListener

38
Event Sources,
Listeners, and Objects

39
Class hierarchy and methods
• java.util.EventListener
• java.awt.event.ActionListener
– actionPerformed
• java.awt.event.AdjustmentListener
– adjustmentValueChanged
• java.awt.event.ComponentListener
– componentHidden, componentMoved, componentResized,
componentShown
• java.awt.event.FocusListener
– focusGained, focusLost
• java.awt.event.ItemListener
– itemStateChanged 40
Continued…
• java.awt.event.KeyListener
– keyPressed, keyReleased, keyTyped
• java.awt.event.MouseListener
– mouseEntered, mouseExited, mousePressed, mouseReleased,
mouseClicked
• java.awt.event.MouseMotionListener
– mouseDragged, mouseMoved
• java.awt.event.TextListener
– textValueChanged
• java.awt.event.WindowListener
– windowOpened, windowClosing, windowClosed, windowActivated,
windowDeactivated, windowIconified, windowDeiconified

41
Event Sources and
Their Listeners
• Component (ALL components extend this)
– ComponentListener, FocusListener, KeyListener, MouseListener,
MouseMotionListener
• Dialog - WindowListener
• Frame - WindowListener
• Button - ActionListener
• Choice - ItemListener
• Checkbox - ItemListener
• CheckboxMenuItem - ItemListener
• List - ItemListener, ActionListener
• MenuItem - ActionListener
• Scrollbar - AdjustmentListener
• TextField - ActionListener, TextListener
• TextArea - TextListener
42
Continued…
• This invocation happens automatically; you will not
see the code corresponding to the method
invocation.
• However, you must specify two things:
– For each JButton, you must specify the corresponding
listener object. In Java, this is known as registering the
listener.
– You must define the methods that will be invoked when
the event is sent to the listener. Normally, you will write
these methods and you will never write the code for
invocation.
43
Continued...
• Java provides various classes to handle different
kinds of events.
• The action event is handled by the class
ActionListener, which contains only the method
actionPerformed.
• In the method actionPerformed, you include the
code that you want the system to execute when
an action event is generated.

44
Continued…
• The class ActionListener that handles the action event is
a special type of class, called an interface.
• An interface is a class that contains only the method
headings, and each method heading is terminated with
a semicolon.
• For example, the definition of the interface
ActionListener containing the method actionPerformed
is:
public interface ActionListener {
public void actionPerformed(ActionEvent e);
}.
45
Continued…
• Because the method actionPerformed does not contain a
body, Java does not allow you to instantiate an object of
type ActionListener.
• Because you cannot instantiate an object of type
ActionListener, first you need to create a class on top of
ActionListener so that the required object can be
instantiated.
• The class created must provide the necessary code for the
method actionPerformed.
• You will create the class CalculateButtonHandler to handle
the event generated by clicking the button calculateB.
46
Continued…
• The class CalculateButtonHandler is created
on top of the interface ActionListener.
• The definition of the class
CalculateButtonHandler is:
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//The code for calculating the area and the perimeter
//and displaying these quantities goes here
}
}
47
Continued…
• To create a listener object of type
CalculateButtonHandler.
• Consider the following statements:
• CalculateButtonHandler cbHandler;
• cbHandler = new CalculateButtonHandler(); //instantiate the object
• Having created a listener, you next must associate (or in Java terminology,
register) this handler with the corresponding JButton.
• The following line of code registers cbHandler as the listener object of
calculateB:
• calculateB.addActionListener(cbHandler);

48
Continued…
• The complete definition of the class CalculateButtonHandler,
including the code for the method actionPerformed, is:
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area, perimeter;
Length = Double.parseDouble(lengthTF.getText());
Width = Double.parseDouble(widthTF.getText());
area = length * width;
perimeter = 2 * (length + width);
areaTF.setText("" + area);
perimeterTF.setText("" + perimeter);
}
}
49
Continued…
• To create and register an action event listener:
1. Created a class that implements the interface ActionListener. For example,
for the JButton calculateB we created the class CalculateButtonHandler.
2. Provided the definition of the method actionPerformed within the class
that you created in Step 1. The method actionPerformed contains the
code that the program executes when a specific event is generated. For
example, when you click the JButton calculateB, the program should
calculate and display the area and perimeter of the rectangle.
3. Created and instantiated an object of the class type created in Step 1. For
example, for the JButton calculateB we created the object cbHandler.
4. Registered the event handler created in Step 3 with the object that
generates an action event using the method addActionListener. For
example, for JButton calculateB the following statement registers the
object cbHandler to listen and register the action event:
calculateB.addActionListener(cbHandler);
50
Continued…
• To create and register the action listener with the JButton
exitB.
private class ExitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
• The following statements create the action listener object for
the button exitB:
• ExitButtonHandler ebHandler;
• ebHandler = new ExitButtonHandler();
• exitB.addActionListener(ebHandler);
51
Continued…
• The interface ActionListener is contained in
the package java.awt.event.
• Therefore, to use this interface to handle
events, your program must include the
statement:
• import java.awt.event.*;
• or:
• import java.awt.event.ActionListener;

52
Complete Code for the example
• /Given the length and width of a rectangle, this Java
• //program determines its area and perimeter.
• import javax.swing.*;
• import java.awt.*;
• import java.awt.event.*;
• public class RectangleProgram extends JFrame{
• private JLabel lengthL, widthL, areaL, perimeterL;
• private JTextField lengthTF, widthTF, areaTF, perimeterTF;
• private JButton calculateB, exitB;
• private ButtonHandler cbHandler;
• private ExitButtonHandler ebHandler;
• private static final int WIDTH = 400;
• private static final int HEIGHT = 300;
• public RectangleProgram(){
• //Create the four labels
• lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
• widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
• areaL = new JLabel("Area: ", SwingConstants.RIGHT);
• perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
• //Create the four text fields
• lengthTF = new JTextField(10);
• widthTF = new JTextField(10);
• areaTF = new JTextField(10);
• perimeterTF = new JTextField(10);
• //Create Calculate Button
• calculateB = new JButton("Calculate");
• cbHandler = new ButtonHandler();
• calculateB.addActionListener(cbHandler);
• //Create Exit Button
• exitB = new JButton("Exit");
• ebHandler = new ExitButtonHandler();
• exitB.addActionListener(ebHandler); 53
• //Set the title of the window
• //Get the container
Continued…
• Container pane = getContentPane();
• //Set the layout
• pane.setLayout(new GridLayout(5, 2));
• //Place the components in the pane
• pane.add(lengthL);
• pane.add(lengthTF);
• pane.add(widthL);
• pane.add(widthTF);
• pane.add(areaL);
• pane.add(areaTF);
• pane.add(perimeterL);
• pane.add(perimeterTF);
• pane.add(calculateB);
• pane.add(exitB);
• //Set the size of the window and display it
• setSize(WIDTH, HEIGHT);
• setVisible(true);
• setDefaultCloseOperation(EXIT_ON_CLOSE);
• }
• private class ButtonHandler implements ActionListener{
• public void actionPerformed(ActionEvent e){
• double width, length, area, perimeter;
• length = Double.parseDouble(lengthTF.getText());
• width = Double.parseDouble(widthTF.getText());
• area = length * width;
• perimeter = 2 * (length + width);
• areaTF.setText("" + area);
• perimeterTF.setText("" + perimeter);
• }
• }
• private class ExitButtonHandler implements ActionListener
• {
• public void actionPerformed(ActionEvent e){
• System.exit(0);
• }
• }
• public static void main(String[] args){
54
• RectangleProgram rectObject = new RectangleProgram();
• }
I/O Streams Basics
• Java programs perform I/O through streams
• An I/O Stream represents an input source or an
output destination
• A stream can represent many different kinds of
sources and destinations, including disk files,
devices, other programs, etc.
• Streams support many different kinds of data,
including simple bytes, primitive data types,
localized characters, and objects.
55
Continued…
• A stream is a sequence of data.
• The most basic actions are sending data to a
stream or receiving data from a stream.
• A program uses an input stream to read data
from a source :

56
Continued…
• A program uses an output stream to write
data to a destination:

57
Types of Streams
• Byte Streams
– InputStream
• FileInputStream
– OutputStream
• FileOutputStream
• Character Streams
– Reader
• FileReader
– Writer
• FileWriter
• Buffered Streams
– BufferedReader
– BufferedWriter
58
Continued…

59
Continued…

60
ByteStreams
• Byte-based streams input and output data in its binary format.
• Java defines two classes for byte stream:
– InpustStream
– OuputStream
• InputStream class is the super class of all the classes which are
used to read data in the form of bytes.
• E.g. InputStream, FileInputStream, BufferedInputStream,
DataInputStream
• OutputStream class is the super class of all the classes which
are used to write data in the form of bytes.
• E.g. OutputStream, FileOutputStream, BufferedOutputStream,
DataOutputStream
61
Continued…
• Programs use byte streams to perform input
and output of 8-bit bytes.
• All byte stream classes are descended from
InputStream and OutputStream.
• Examples
– FileInputStream
– FileOutputStream

62
Character Streams
• Character-based streams input and output data as a
sequence of characters.
• Character streams are defined by two classes:
– Reader
– Writer
• Reader class is the super class of all the classes which are
used to read data in the form of characters.
• E.g. Reader, BufferedReader, InputStreamReader, etc..
• Writer class is the super class of all the classes which are used
to write data in the form of characters.
• E.g. Writer, BufferedWriter, PrintWriter etc…
63
Continued…
• All character stream classes are descended from
Reader and Writer
• Character streams are often "wrappers" for byte
streams
• The character stream uses the byte stream to
perform the physical I/O, while the character
stream handles translation between characters and
bytes
• FileReader, for example, uses FileInputStream,
while FileWriter uses FileOutputStream
64
Buffered Streams
• Both byte and character streams use unbuffered
I/O.
• This means each read or write request is handled
directly by the underlying OS
• This can make a program much less efficient, since
each such request often triggers disk access,
network activity, or some other operation that is
relatively expensive
• To reduce this kind of overhead, the Java platform
implements buffered I/O streams
65
Continued…
• Buffered input streams read data from a memory
area known as a buffer;
• Similarly, buffered output streams write data to a
buffer,
• A program can convert a unbuffered stream into a
buffered stream using the wrapping
– inputStream = new BufferedReader(new
FileReader(“sample.txt"));
– outputStream = new BufferedWriter(new
FileWriter("output.txt")); 66
Continued…
• There are four buffered stream classes used to
wrap unbuffered streams:
– BufferedInputStream and BufferedOutputStream
create buffered byte streams, while
– BufferedReader and BufferedWriter create
buffered character streams

67
Sample FileWriter
• import java.io.*;
• public class FWriter{

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

• FileWriter writer = new FileWriter("d:/program.c");


• writer.write("/* ... c code ... */ ");
• writer.write("This is a sample Java Program");
• writer.close();
• }
• }
68
Sample FileReader
• import java.io.*;
• public class FReader{

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

• FileReader reader = new FileReader("d:/program.c");


• BufferedReader br= new BufferedReader(reader);
• String c;
• while((c = br.readLine()) !=null){
• System.out.println(c);
• }
• reader.close();
• }
• }
69
Continued…
• Basic methods in InputStream Abstract class:
• Int read();-Reads a byte of data from this input
stream
• Int read(byte b[]);- Reads up to b.length bytes of
data from this input stream into an array of bytes
• Void close();-Closes the file input and output
streams and releases any system resources
associated with the stream

70
Continued…
• Basic methods in OutputStream Abstract class:
• Void write(int b);- Writes the specified byte to
this file output stream
• Void write(byte b[]);-Writes b.length bytes
from the specified byte array to this file output
stream
• Void close();-Closes the file input and output
streams and releases any system resources
associated with the stream
71
Reading characters
• In Java, console input is accompolished by reading
from System.in
• To obtain a character based stream that is attached
to the console, wrap System.in in a BufferedReader
object.
– BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
• To read characters from BufferedReader use read().
• Each time read() is called it will read characters from
the inputstream and returns it as an integer value.
72
Continued…
• Import java.io.*;
• Class BRRead{
• Public static void main(String[] args)throws IOException{
• Char c;
• BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
• System.out.println(“Enter character,’q’ to quit”);
• //read characters
• Do{
• C=(char) br.read();
• System.out.println(c);
• }while(c!=‘q’);
• }
• }
73
Reading /Writing Files
• Java provides a number of classes and methods
that allows reading and writing to files.
• Two of the most often used stream classes are:
– FileInputStream
– FileOutputStream
• To open a file you simply creat an an object of
one of these classes specifying the names of
the file as an argument to the constructors:
– FileInputStream(String fileName)
– FileOutputStream(String fileName)
74
Continued…
• Import java.io.*;
• Class ShowFile{
• Public static void main(String[] args)throws IOException{
• Int i;
• FileInputStream fin;
• Try{
• Fin=new FileInputStream(args[0]);
• }catch(FileNotFoundException e){
• System.out.println(“File not Found”);
• Return;
• }catch(ArrayIndexOutOfBoundException e){
• System.out.println(“Usage: Show File”);
• Return;
• }
• //read characters unitl eof
• Do{
• i=fin.read();
• If(i!=-1)
• System.out.println((char) i);
• }while(i!=-1)
• Fin.close();
• }
• } 75
Sample program
• import java.io.File;
• import java.io.FileOutputStream;
• import java.io.IOException;
• public class WriteFileExample{
• public static void main(String[] args)throws IOException{

• File file = new File("c:/newfile.txt");
• String content = "This is the text content is updated";
• FileOutputStream fop = new FileOutputStream(file);

• try {
• // if file doesn't exists, then create it
• if (!file.exists()) {
• file.createNewFile();
• }
• // get the content in bytes
• byte[] contentInBytes = content.getBytes();

• fop.write(contentInBytes);
• fop.flush();
• fop.close();

• System.out.println("Done");

• } catch (IOException e) {
• e.printStackTrace();
• }
76
• }
Example
• import java.io.File;
• import java.io.IOException;
• import java.util.Scanner;

• public class CreateNewFile{

• public static void main(String[] args){

• Scanner sc= new Scanner(System.in);

• System.out.println("Enter the file name to create including the path");


• String fn=sc.nextLine();

• File file= new File(fn);

• try{
• boolean b = file.createNewFile();

• if(b==true)
• System.out.println("File is created");
• else
• System.out.println("File is already exists");
• }catch(FileNotFoundException fne){
• System.out.println("Error"+fne.getMessage());
• }
• }
• 77
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy