Powered by Blogger.

The Collection API of Java Platform | List of Java APIs

Introduction of API:-

As the name indicates, collections is a group of objects known as its elements. Basically it is a package of data structures that includes Array Lists, Linked Lists, Hash Sets, etc. A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically, it represents data items that form a natural group and allows duplicate elements while others do not. It consists of both ordered and unordered elements. There is no direct implementation of this interface however SDK provides implementations of more specific sub interfaces like Set and List. The manipulation and passing of collections is done by this interface.

The Two "standard" constructors should be provided by all the general-purpose Collection implementation classes. These classes typically implement Collection indirectly through one of its sub interfaces.

   1. Void (no arguments) constructor which creates an empty collection.

   2. Constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

The user can copy any collection using void constructor to produce an equivalent collection of the desired implementation type. As interfaces cannot contain constructors there is no way to enforce this convention. However all of the general-purpose Collection implementations comply this in the Java platform libraries.

The Java Collections API:

Java Collections of API (Application Programming Intreface) Consists of several interfaces, and classes that implement those interfaces, within the java.util package. It provides tools for maintaining a data container of objects. Each primitive value must be wrapped in an object of its appropriate wrapper class (Boolean, Character, Integer, Double, etc.) to maintain a collection of primitive data. It is an alternative tool to the creation of custom data structures.

You must be familiar with collections if you have worked with Java programming language. Collection implementations included Vector, Hashtable, and array are available in earlier (pre-1.2) versions of the Java platform, but those versions do not include the collections framework. Hence the new version of the Java platform contains the collections framework.

The Collection API:-

A collection is a single object representing a group of objects. The objects in the collection are called elements. Implementation of collection determine whether there is specific ordering and whether duplicates are permitted.

1. Set An unordered collection, where no duplicates are permitted.

2. List An ordered collection, where duplicates are permitted.

1  import java.util.*;
2
3  public class SetExample{
4    public static void main(String[]agrs){
5      Set set = new HashSet();
6      set.add(”One”);
7      set.add(”2nd”);
8      set.add(”3rd”);
9      set.add(new Integer(6));
10     set.add(new Float(7.7F));
11     set.add(”2nd”); // duplicate are not added
12     System.out.println(set);
13   }
14 }

1  import java.util.*;
2
3  public class ListExample{
4    public static void main(String[]agrs){
5      List list = new ArrayList();
6      list.add(”One”);
7      list.add(”2nd”);
8      list.add(”3rd”);
9      list.add(new Integer(6));
10     list.add(new Float(7.7F));
11     list.add(”2nd”); // duplicate is added
12     System.out.println(list);
13   }
14 }

Related Tags for Introduction to Collections API:

c, array, list, collections, data, hash, object, lists, io, objects, include, struct, link, collection, arraylist, structure, sets, name, package, set, element, includes, group, basic, elements, call, hashset, ical, sh, e, it, des, structures, li, in, no, cal, as, m, nt, tr, ca, linked, j, pack, cl, es, sts, em, all, age, me, obj, ack, cat, s, col, at, pac, k, inc, is, ink, ha, ll, collect, ray, ar, collect, str, s, s, th, st, hat, cts, etc, etc, indic, je, ica, ica, nd, on, ol, o.

Thread.sleep() in Java - Thread Sleep Method in Java

Thread Sleep Method in Java:

Syntax:

      public static void Sleep(
      int millisecondsTimeout
      )

Parameters:

millisecondsTimeout
Type: System.Int32

The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.

Examples:

        The following example uses the Sleep method to block the application's main thread.

using System;
using System.Threading;

class Example
{
    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Sleep for 2 seconds.");
            Thread.Sleep(2000);
        }

        Console.WriteLine("Main thread exits.");
    }
}

/* This example produces the following output:

Sleep for 2 seconds.
Sleep for 2 seconds.
Sleep for 2 seconds.
Sleep for 2 seconds.
Sleep for 2 seconds.
Main thread exits.
 */

Threading:

This chapter is excerpted from C# 3.0 in a Nutshell, Third Edition: A Desktop Quick Reference by Joseph Albahari, Ben Albahari, published by O'Reilly Media C# 3.0 in a Nutshell, Third Edition Logo Buy Now C# allows you to execute code in parallel through multithreading.

A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer, threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application domain. This, in part, is why threading is useful: one thread can fetch data in the background while another thread displays the data as it arrives.

This chapter describes the language and Framework features for creating, configuring, and communicating with threads, and how to coordinate their actions through locking and signaling. It also covers the predefined types that assist threading: BackgroundWorker, ReaderWriterLock, and the Timer classes.


Threading's Uses and Misuses:

A common use for multithreading is to maintain a responsive user interface while a time-consuming task executes. If the time-consuming task runs on a parallel "worker" thread, the main thread is free to continue processing keyboard and mouse events.

Whether or not a user interface is involved, multithreading can be useful when awaiting a response from another computer or piece of hardware. If a worker thread performs the task, the instigator is immediately free to do other things, taking advantage of the otherwise unburdened computer.

Another use for multithreading is in writing methods that perform intensive calculations. Such methods can execute faster on a multiprocessor or multicore computer if the workload is shared among two or more threads. Asynchronous delegates are particularly well suited to this. (You can test for the number of processors via the Environment. Processor Count property.)

Some features of the .NET Framework implicitly create threads. If you use ASP.NET, WCF, Web Services, or Remoting, incoming client requests can arrive concurrently on the server. You may be unaware that multithreading is taking place; unless, perhaps, you use static fields to cache data without appropriate locking, running afoul of thread safety.

Threads also come with strings attached. The biggest is that multithreading can increase complexity. Having lots of threads does not in itself create complexity; it's the interaction between threads (typically via shared data) that does. This applies whether or not the interaction is intentional, and can cause long development cycles and an ongoing susceptibility to intermittent and nonreproducible bugs. For this reason, it pays to keep interaction to a minimum, and to stick to simple and proven designs wherever possible. This chapter is largely on dealing with just these complexities; remove the interaction and there's relatively little to say!

Threading also comes with a resource and CPU cost in allocating and switching threads. Multithreading will not always speed up your application-it can even slow it down if used excessively or inappropriately. For example, when heavy disk I/O is involved, it can be faster to have a couple of worker threads run tasks in sequence than to have 10 threads executing at once. (In the later section "the section called "Signaling with Wait and Pulse" we describe how to implement a producer/consumer queue, which provides just this functionality.)

Getting Started:

A C# program starts in a single thread that's created automatically by the CLR and operating system (the "main" thread). Here it lives out its life as a single-threaded application, unless you do otherwise, by creating more threads (directly or indirectly).

The simplest way to create a thread is to instantiate a Thread object and to call its Start method. The constructor for Thread takes a Thread Start delegate: a parameterless method indicating where execution should begin. Here's an example:

class ThreadTest
{
  static void Main(  )
  {
    Thread t = new Thread (WriteY);          // Kick off a new thread
    t.Start();                               // running WriteY(  )

    // Simultaneously, do something on the main thread.
    for (int i = 0; i < 1000; i++) Console.Write ("x");
  }

  static void WriteY(  )
  {
    for (int i = 0; i < 1000; i++) Console.Write ("y");
  }
}

// Output:
xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
............

The sleep() is a static method in the Thread class, it operates on the current thread and is referred to as Thread.sleep(x); where x is the minimum number of millisecond.

1  public class ThreadSleep implements Runnable{
2     public void run(){
3       int i=1;
4       while(i<=10){
5         System.out.println(”i:”+i);
6         i++;
7         try{
8            Thread.sleep(300);
9         }catch(InterruptedException e){
10           System.out.println(e);
11        }
12      }
13   }
14
15   public static void main (String[]args){
16     ThreadSleep ts = new ThreadSleep();
17     Thread thread1 = new Thread(ts);
18     Thread thread2 = new Thread(ts);
19     Thread thread3 = new Thread(ts);
20     thread1.start();
21     thread2.start();
22     thread3.start();
23   }
24 }

Synchronization:

So far, we've described how to start a task on a thread, how to configure a thread, and how to pass data in both directions. We've also described how local variables are private to a thread and how references can be shared among threads allowing them to communicate via common fields.

The next step is synchronization: coordinating the actions of threads for a predictable outcome. Synchronization is particularly important when threads access the same data; it's surprisingly easy to run aground in this area.

Synchronization constructs can be divided into four categories:

Simple Blocking Methods

These wait for another thread to finish or for a period of time to elapse. Sleep, Join, and EndInvoke are simple blocking methods.

Locking constructs:

These enforce exclusive access to a resource, such as a field or section of code, ensuring that only one thread can enter at a time. Locking is the primary thread-safety mechanism, allowing threads to access common data without interfering with each other. The locking constructs are lock and Mutex (and a variation called Semaphore).

Signaling constructs:

These allow a thread to pause until receiving a notification from another, avoiding the need for inefficient polling. There are two signaling devices: event wait handles and Monitor's Wait/Pulse methods.

Nonblocking synchronization constructs:

These protect access to a common field by calling upon processor primitives. The Interlocked class and the volatile keyword are the two constructs in this category.

Blocking is essential to all but the last category. Let's briefly examine this concept.

Code: The StackTest.java application

1   class MyStack{
2     private int idx=0;
3     private char[] data = new char[6];
4
5     public synchronized void push(char c){
6      this.notify();
7      if(idx !=5){
8         data[idx]=c;
9         idx++;
10     }
11   }
12
13   public synchronized char pop(){
14     if(idx==0){
15        try{
16           this.wait();
17        }catch(InterruptedException e ){
18           System.out.println(e);
19        }
20     }
21     idx−−;
22     return data[idx];
23   }
24 }
25
26 class Producer implements Runnable{
27   private MyStack stack;
28
29   public Producer(MyStack s){
30     stack = s;
31   }
32
33   public void run(){
34     char c;
35     for(int i=0; i<50; i++){
36         c = (char) (Math.random()*26+’A’);
37         stack.push(c);
38         System.out.println(”Producer:”+c);
39         try{
40            Thread.sleep((int)(Math.random()*300));
41         }catch(InterruptedException e){
42            System.out.println(e);
43         }
44      }
45    }
46  }
47


48  class Consumer implements Runnable{
49    private MyStack stack;
50
51    public Consumer(MyStack s){
52      stack = s;
53    }
54
55    public void run(){
56      char c;
57      for(int i=0; i<50; i++){
58          c = stack.pop();
59          System.out.println(”Consumer:”+c);
60          try{
61             Thread.sleep((int)(Math.random()*300));
62          }catch(InterruptedException e){
63             System.out.println(e);
64          }
65      }
66    }
67 }
68
69 public class StackTest{
70   public static void main(String[]args){
71     MyStack s = new MyStack();
72     Producer p = new Producer(s);
73     Thread t1 = new Thread(p);
74     t1.start();
75     Consumer c = new Consumer(s);
76     Thread t2 = new Thread(c);
77     t2.start();
78   }
79 }

Locking:

Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time. The .NET Framework provides two exclusive locking constructs: lock and Mutex. Of the two, the lock construct is faster and more convenient. Mutex, though, has a niche in that its lock can span applications in different processes on the computer.

This section focuses on the lock construct; later we show how Mutex can be used for cross-process locking. Finally, we introduce Semaphore, .NET's nonexclusive locking construct.

Let's start with the following class:

class ThreadUnsafe
{
  static int val1, val2;

  static void Go(  )
  {
    if (val2 != 0) Console.WriteLine (val1 / val2);
    val2 = 0;
  }
}

This class is not thread-safe: if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error, because val2 could be set to zero in one thread right as the other thread was in between executing the if statement and Console. Write Line.

Here's how lock can fix the problem:

class ThreadSafe
{
  static object locker = new object(  );
  static int val1, val2;

  static void Go(  )
  {
    lock (locker)
    {
      if (val2 != 0) Console.WriteLine (val1 / val2);
      val2 = 0;
    }
  }
}

Only one thread can lock the synchronizing object (in this case, locker) at a time, and any contending threads are blocked until the lock is released. If more than one thread contends the lock, they are queued on a "ready queue" and granted the lock on a first-come, first-served basis. Exclusive locks are sometimes said to enforce serialized access to whatever's protected by the lock, because one thread's access cannot overlap with that of another. In this case, we're protecting the logic inside the Go method, as well as the fields val1 and val2.

A thread blocked while awaiting a contended lock has a Thread State of Wait Sleep Join. In the section "the section called "Interrupt and Abort"," later in this chapter, we describe how a blocked thread can be forcibly released via another thread. This is a fairly heavy-duty technique that might be used in ending a thread.

C#'s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try-finally block. Here's what's actually happening within the Go method of the preceding example:

Monitor.Enter (locker);
try
{
  if (val2 != 0) Console.WriteLine (val1 / val2);
  val2 = 0;
}
finally { Monitor.Exit (locker); }

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.

Monitor also provides a Try Enter method that allows a timeout to be specified, either in milliseconds or as a Time Span. The method then returns true if a lock was obtained, or false if no lock was obtained because the method timed out. Try Enter can also be called with no argument, which "tests" the lock, timing out immediately if the lock can't be obtained right away.


Nested Locking:

A thread can repeatedly lock the same object, via multiple calls to Monitor.Enter, or nested lock statements. The object is subsequently unlocked when a corresponding number of Monitor.Exit statements have executed or when the outermost lock statement has exited. This allows for the most natural semantics when one method calls another as follows:

static object x = new object(  );

static void Main(  )
{
  lock (x)
  {
     Console.WriteLine ("I have the lock");
     Nest(  );
     Console.WriteLine ("I still have the lock");
  }
  // Now the lock is released.
}

static void Nest(  )
{
  lock (x) { }
  // We still have the lock on x!
}

A thread can block on only the first, or outermost, lock.

Java Code: Threading in Java Programming in The Real World

Java Threads:

Modern computer performs multiple jobs at the same time. Thread is the process of multi-tasking using CPU, which performs computations. A thread or execution context is composed of three main parts:

1. A virtual CPU.
2. The code that the CPU executes.
3. The data on which the code work.

Thread object for each Runnable:

       Thread thr1 = new Thread(r1);
       Thread thr2 = new Thread(r2);
       thr1.start();
       thr2.start();

The class java.lang.Thread enables us to create and control threads. A process is a program in execution. One or more threads a process. A thread is composed of CPU, code, and data. Code can share multiple threads, two threads can share the same code. We can create thread by implementing Runnable interface (Code 5-1) or by extending Thread class (Code 5-2). Thread class implements the Runnable interface itself. The Runnable interface provides the public void run() method. We override the run() method, which contain the code for CPU execution.

A newly created thread does not start running automatically, we must call its start() method.

1 public class ThreadTest implements Runnable{
2   public void run(){
3     int i =1;
4     while(i<=100){
5        System.out.println(”i:”+i);
6        i++;
7     }
8   }
9
10  public static void main(String[]args){
11    ThreadTest t = new ThreadTest();
12    Thread thread1 = new Thread(t);
13    Thread thread2 = new Thread(t);
14    Thread thread3 = new Thread(t);
15    thread1.start();
16    thread2.start();
17    thread3.start();
18  }
19 }


1  public class MyThread extends Thread{
2    public void run(){
3      int i=1;
4      while(i<=100){
5        System.out.println(”i:”+i);
6        i++;
7      }
8   }
9
10  public static void main(String[]args){
11    Thread thread1 = new MyThread();
12    Thread thread2 = new MyThread();
13    Thread thread3 = new MyThread();
14    thread1.start();
15    thread2.start();
16    thread3.start();
17  }
18 }

Getting started: what are threads, and how to use them in Java:

It's easier to illustrate what a thread is by diving straight in and seeing some code. We're going to write a program that "splits itself" into two simultaneous tasks. One task is to print Hello, world! every second. The other task is to print Goodbye, cruel world! every two seconds. OK, it's a silly example.

For them to run simultaneously, each of these two tasks will run in a separate thread. To define a "task", we create an instance of Runnable. Then we will wrap each of these Runnables around a Thread object.
Runnable

A Runnable object defines an actual task that is to be executed. It doesn't define how it is to be executed (serial, two at a time, three at a time etc), but just what. We can define a Runnable as follows:

Runnable r = new Runnable() {
  public void run() {
    ... code to be executed ...
  }
};

Runnable is actually an interface, with the single run() method that we must provide. In our case, we want the Runnable.run() methods of our two tasks to print a message periodically. So here is what the code could look like:

Runnable r1 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Hello, world!");
        Thread.sleep(1000L);
      }
    } catch (InterruptedException iex) {}
  }
};
Runnable r2 = new Runnable() {
  public void run() {
    try {
      while (true) {
        System.out.println("Goodbye, " +
        "cruel world!");
        Thread.sleep(2000L);
      }
    } catch (InterruptedException iex) {}
  }
};

For now, we'll gloss over a couple of issues, such as how the task ever stops. As you've probably gathered, the Thread.sleep() method essentially "pauses" for the given number of milliseconds, but could get "interrupted", hence the need to catch InterruptedException. We'll come back to this in more detail in the section on Thread interruption and InterruptedException. The most important point for now is that with the Runnable() interface, we're just defining what the two tasks are. We haven't actually set them running yet. And that's where the Thread class comes in.

Java: Drawing Lines, Rectangles, and Ovals Java Applet Program

Drawing Lines, Rectangles, and Ovals Java Applet:-

Code 4-15 presents a variety if Graphics methods for drawing lines, rectangles, and ovals.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestLineRectOval extends JFrame{
   private static final long serialVersionUID=0;

   public TestLineRectOval(){
     super(”Lines Ractangles Ovals”);
     setSize(360, 450);
     show();
   }

   public void paint(Graphics g){
     g.setColor(Color.red);
     g.drawLine(50, 40, 300, 40);

     g.setColor(Color.blue);
     g.drawRect(50 ,60, 100, 60);
     g.fillRect(200, 60, 100, 60);

     g.setColor(Color.cyan);
     g.drawRoundRect(50, 150, 100, 60, 50, 50);
     g.fillRoundRect(200, 150, 100, 60, 50, 50);

     g.setColor(Color.yellow);
     g.draw3DRect(50, 250, 100, 60, true);
     g.fill3DRect(200, 250, 100, 60, true);

     g.setColor(Color.magenta);
     g.drawOval(50, 350, 100, 60);
     g.fillOval(200, 350, 100, 60);
   }

   public static void main(String[]args){
     TestLineRectOval tlro = new TestLineRectOval();
     tlro.addWindowListener(
       new WindowAdapter(){
         public void windowClosing(WindowEvent e){
           System.exit(0);
         }
       }
     );
   }
 }

Code 4-16 provides an password example using Jlabel, JtextField, JpasswordField, and Jbutton.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class Password extends JFrame{
   private static final long serialVersionUID=0;

   private JLabel l1, l2;
   private JTextField t1;
   private JPas swordField pw;
   private JButton b1, b2;

   public Password(){
     super(”Password Example”);
     Container c = getContentPane();
     c.setLayout(new FlowLayout());

     l1 = new JLabel(”Enter User Name”);
     c.add(l1);

     t1 = new JTextField(15);
     c.add(t1);

     l2 = new JLabel(”Enter Password”);
     c.add(l2);

     pw = new JPas swordField(10);
     c.add(pw);

     b1 = new JButton(”Enter”);
     b1.addActionListener(
       new ActionListener(){
         public void actionPerformed(ActionEvent e){
           if(t1.getText().equals(”Parvez”) && pw.getText(). equals (”123456
              JOptionPane.showMessageDialog(null, ”Welcome to Java”);
           }else{
              JOptionPane.showMessageDialog(null, ”Incorrect user name 38
           }
         }
       }
     );
     c.add(b1);

     b2 = new JButton (”Cancel”);
     b2.addActionListener(
       new ActionListener(){
          public void actionPerformed(ActionEvent e){
             String s = ” ”;
             t1.setText(s);
             pw.setText(s);
          }
       }
     );
     c.add(b2);

     setSize(300, 125);
     show();
     }

     public static void main(String[]args){
       Password PW = new Password();
       PW.addWindowListener(
         new WindowAdapter(){
           public void windowClosing(WindowEvent e){
              System.exit(0);
           }
         }
       );
     }
  }


Example of Jcomponents such as: JcheckBox, JradioButton, JcomboBox, Jlist, and JTextArea provided in code 4-17.

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestJComt extends JFrame{
   private static final long serialVersionUID=0;

   private JCheckBox bold, italic;
   private JRadioButton male, female;
   private ButtonGroup radioGroup;
   private JComboBox cBox;
   private String[]str 1 = {”spring”, ”summer”, ”fall”};
   private JList colorList;
   private String[]str 2 = {”Red”, ”Green”, ”Blue”, ”Black”, ”White”, ”15 ”Orange”, ”Pink”, ”Magenta”, ”Sky”, ”Cyan 16 private JTextArea ta1;

   public TestJComt(){
     super(”Test JComponents”);
     Container c = getContentPane();
     c.setLayout(new FlowLayout());

     bold = new JCheckBox(”Bold”);
     c.add(bold);
     italic = new JCheckBox(”Italic”);
     c.add(italic);

     male = new JRadioButton(”Male”);
     c.add(male);
     female = new JRadioButton(”Female”);
     c.add(female);
     radioGroup = new ButtonGroup();
     radioGroup.add(male);
     radioGroup.add(female);

     cBox = new JComboBox(str 1);
     c.add(cBox);

     colorList = new JList(str 2);
     colorList.setVisibleRowCount(5);
     c.add(new JScrollPane(colorList));

     String s = ”Java is a object oriented programming language”;
     ta1 = new JTextArea(s, 10, 15);
     c.add(new JSc rollPane(ta1));

     setSize(200, 350);
     show();
   }

   public static void main(String[]args){
     TestJComt jc = new TestJComt ();
     jc.addWindowListener(
       new WindowAdapter(){
         public void windowClosing(WindowEvent e){
           System.exit(0);
         }
       }
     );
   }
 }

Using Example:

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class OpenFile extends JFrame{
   private static final long serialVersionUID=0;
   private JButton b1;
   private JFileChooser jfc;

   public OpenFile(){
     super(”File Opener”);
     b1 = new JButton(”Open File Chooser”);
     b1.addActionListener(
       new ActionListener(){
          public void actionPer formed( ActionEvent e){
            abc();
          }
       }
     );
     getContentPane().add(b1, BorderLayout.NORTH);
     setSize(300, 200);
     show();
     }

     private void abc(){
       jfc = new JFileChooser();
       jfc.showOpenDialog(this);
     }

     public static void main(String[]args){
       OpenFile of = new OpenFile();
       of.addWindowListener(
          new WindowAdapter(){
              public void windowClosing(WindowEvent e){
                System.exit(0);
              }
          }
       );
     }
  }

Java:~ code for change Font in javaScript Program

Description:

The java.awt.Font class is used to create Font objects to set the font for drawing text, labels, text fields, buttons, etc.

Example:

       JButton b = new JButton("OK");
       b.setFont(new Font("sansserif", Font.BOLD, 32));

Available System Fonts:

For maximum portability, use the generic font names, but you can use any font installed in the system. It is suggested to use a font family name, and create the font from that, but you can also use the fonts directly. You can get an array of all available font family names or all fonts.

 // Font info is obtained from the current graphics environment.

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

//--- Get an array of font names (smaller than the number of fonts)

String[] fontNames = ge.getAvailableFontFamilyNames();

//--- Get an array of fonts.  It's preferable to use the names above.

Font[] allFonts = ge.getAllFonts();

Using Fonts for Graphics:

      Font f;
      f = new Font(String name, int style, int size);    // creates a new font
name is "Serif", "SansSerif", or "Monospaced", or a font on the system. style is Font.PLAIN. Font.BOLD, Font.ITALIC, or Font.BOLD+Font.ITALIC. size is the point size, typically in the range 8-48.

Example:

Font big = new Font("SansSerif", Font.Bold, 48);
. . .
g.setFont(big);
g.drawString("Greetings Earthling");

Fonts in Java:

In Java, Font class manages the font of Strings. The constructor of Font class takes three arguments: the font name, font style, and font size. The font name is any font currently supported by the system where the program is running such as standard Java fonts Monospaced, SansSerif, and Serif. The font style is Font.PLAIN, Font.ITALIC, or Font.BOLD. Font styles can be used in combination such as: Font.ITALIC + Font.BOLD.

Fonts in Java Example:

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class TestFonts extends JFrame{
   private static final long serialVersionUID=0;

   public TestFonts(){
     super(”Font Examples”);
     setSize(300, 150);
     show();
   }

   public void paint(Graphics g){
     g.drawString(”Welcome to Java.”, 20, 50);
     g.setColor(Color.red);
     g.setFont(new Font(”Monospaced”, Font.BOLD, 14));
     g.drawString(”Welcome to Java.”, 20, 70);
     g.setColor(Color.blue);
     g.setFont(new Font(”SansSerif”, Font.BOLD +Font. ITALIC, 16));
     g.drawString(”Welcome to Java.”, 20, 90);
   }

   public static void main(String[]args){
     TestFonts tf = new TestFonts();
     tf.addWindowListener(
        new WindowAdapter(){
          public void windowClosing(WindowEvent e){
            System.exit(0);
          }
        }
      ) ;
    }
 }

Code for Change Font of Text in Java:

import java.awt.*;
import java.text.*;
import javax.swing.*;
import java.awt.font.*;

public class ShowColorAndFont extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    String text = "Java is an Object Oriented Programming Language.";
    Dimension dimension = getSize();

    Font font1 = new Font("Book Antiqua", Font.PLAIN, 30);
    Font font2 = new Font("Monotype Corsiva", Font.PLAIN, 30);

    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, font1);
    attributedString.addAttribute(TextAttribute.FONT, font2, 1, 4);
   attributedString.addAttribute(TextAttribute.FONT, font2, 6, 7);
   attributedString.addAttribute(TextAttribute.FONT, font2, 9, 10);
   attributedString.addAttribute(TextAttribute.FONT, font2, 12, 17);
   attributedString.addAttribute(TextAttribute.FONT, font2, 19, 26);
   attributedString.addAttribute(TextAttribute.FONT, font2, 28, 38);
   attributedString.addAttribute(TextAttribute.FONT, font2, 40, 47);

  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 0, 1);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 5, 6);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 8, 9);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 11, 12);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 18, 19);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 27, 28);
  attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red, 39, 40);
  
    g2d.drawString(attributedString.getIterator(), 40, 80);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Show Color and Font");
    frame.getContentPane().add(new ShowColorAndFont());
    frame.setSize(700, 200);
    frame.show();

  }

Java Program: Using Layout Managers Example

Layout Managers:

In Java programming, the layout manager manages the layout of components in a container, which we can change by calling setLayout() method. The layout manage is responsible for deciding the layout policy and size of each of its container’s child components. The following layout managers are included with the Java programming language:

1. FlowLayout The FlowLayout is the default layout manager of Panel and Applet.
2. BorderLayout The BorderLayout is the default layout manager of Window, Dialog, and Frame.
3. Layout The GridLayout provides flexibility for placing components.
4. CardLayout The CardLayout provides functionality comparable to a primitive tabbed panel.
5. GridBagLayout.

FlowLayout manager uses line-by-line technique to place the components in a container. Each time a line is filled, a new line is started. It does not consider the size of components.

 import java.awt.*;
 import java.awt.event.*;

 public class FlowExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3;

   public FlowExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
   }

   public void launchFrame(){
     f.setLayout(new FlowLayout());
     // f.setLayout(new FlowLayout(FlowLayout.LEFT));
     // f.setLayout(new FlowLayout(FlowLayout.RIGHT));
     // f.setLayout(new FlowLayout(FlowLayout.CENTER));
     // f.setLayout(new FlowLayout(FlowLayout.RIGHT,20,30));
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.addWindowListener(this);
     f.setSize(250, 150);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified (WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     FlowExamplefe = new FlowExample();
     fe.launchFrame();
   }
 }

The BorderLayout manager contains five distinct areas: NORTH, SOUTH, EAST, WEST, and CENTER, indicated by BorderLayout.NORTH, and so on:

 import java.awt.*;
 import java.awt.event.*;

 public c lass BorderExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3, b4, b5;

   public BorderExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
     b4 = new Button(”Button 4”);
     b5 = new Button(”Button 5”);
   }

   public void launchFrame(){
     f.add(b1, BorderLayout.NORTH);
     f.add(b2, BorderLayout.SOUTH);
     f.add(b3, BorderLayout.WEST);
     f.add(b4, BorderLayout.EAST);
     f.add( b5,BorderLayout.CENTER);
     f.addWindowListener(this);
     f.setSize(250, 250);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     BorderExample be = new BorderExample();
     be.launchFrame();
   }
 }

The GridLayout manager placing components with a number of rows and columns. The following constructor creates a GridLayout with the specified equal size. new GridLayout(int rows, int cols);

 import java.awt.*;
 import java.awt.event.*;

 public class GridExample implements WindowListener{
   private Frame f;
   private Button b1, b2, b3, b4, b5, b6;

   public GridExample(){
     f = new Frame(”FlowLayout”);
     b1 = new Button(”Button 1”);
     b2 = new Button(”Button 2”);
     b3 = new Button(”Button 3”);
     b4 = new Button(”Button 4”);
     b5 = new Button(”Button 5”);
     b6 = new Button(”Button 6”);
   }

   public void launchFrame(){
     f.setLayout(new GridLayout(3,2));
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.add(b4);
     f.add(b5);
     f.add(b6);
     f.addWindowListener(this);
     f.setSize(300, 300);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified (WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     GridExample ge = new GridExample() ;
     ge.launchFrame();
   }
 }

About Java: Colors in Java Selector

Description:

The java.awt.Color class is used to create new colors, and predefines a few color constants (see below). Java allows the creation of up to 24 million different colors.

Because our eyes have three kinds of neurons that respond primarily to red, green, and blue, it's possible for computer monitors (and TVs) to create all colors using the RGB system. The RGB system Java uses combines red, green, and blue in amounts represented by a number from 0 to 255. For example, red is (255, 0, 0) -- 255 units of red, no green, and no blue. White is (255, 255, 255) and black is (0,0,0).

Color Constants:

Java originally defined a few color constant names in lowercase, which violated the naming rule of using uppercase for constants. These are best to use since they are available in all versions of Java: Color.black, Color.darkGray, Color.gray, Color.lightGray, Color.white, Color.magenta, Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.cyan, Color.blue

Java 1.4 added the proper uppercase names for constants: Color.BLACK, Color.DARK_GRAY, Color.GRAY, Color.LIGHT_GRAY, Color.WHITE, Color.MAGENTA, Color.RED, Color.PINK, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE

Constructor:

Color c = new Color(int red, int green, int blue)

This creates a new color object that is a combination of red, green, and blue. The values of each color must be in the range 0-255.

Don't do anything to a Color:

A Color object is created only to be passed as a parameter. You will never call any Color methods.

Example:

Color c = new Color(255, 255, 240);
this.setBackground(c);

Advanced:

Additional constructors use single packed ints or floating point values. In addition, there is support for the HSB (Hue, Saturation, Brightness) color model and transparency. There is a Color Chooser in Java 2 that lets the user choose a color.   

Colors in Java:

In Java, we can control the colors used for the foreground using setForeground() method and the background using setBackground() method of AWT components. The setForeground() and setBackground() methods take an arguments that is an instance of of java.awt.Color class. We can use the constant colors referred to as Color.red, Color.blue, Color.green, Color.yellow, and so on. We can also construct a specific Color object by specifying the color by a combination of three byte-sized integers (0-255), one for each primary color: red, green, and blue.

Colors in Java Program:

 import java.awt.*;
 import java.awt.event.*;

 public class TestColors implements WindowListener, ActionListener{
private Frame f;
private Button b;

public TestColors(){
f = new Frame(”Frame Title”);
b = new Button(”Change Color”);
b.setActionCommand(”button press”);
}

public void launchFrame(){
b.addActionListener(this);
b.setForeground(Color.red);
b.setBackground(Color.yellow);
f.add(b);
f.addWindowListener(this);
f.setSize(300, 300);
f.setBackground(Color.green);
f.setLayout(new FlowLayout());
f.setVisible(true);
}

public void actionPer formed(ActionEvent e){
int x, y, z;
if(e.getActionCommand()==”button press”){
x = (int) (Math.random()*100);
y = (int) (Math.random()*100);
z = (int) (Math.random()*100);
Color c = new Color(x, y, z);
f.setBackground(c);
}
}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowOpened(WindowEvent e){}
public void windowIconified (WindowEvent e){}
public void windowDeiconified (WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

public static void main(String[]args){
TestColors tc = new TestColors();
tc.launchFrame();
}
}

Colliding Using Mouse Example

This section covers tasks associated with mouse input:

1. Tracking the Mouse Cursor

2. Drawing Lines with the Mouse

3. Processing a Double Click Message

4. Selecting a Line of Text

5. Using a Mouse Wheel in a Document with Embedded Objects

6. Retrieving the Number of Mouse Wheel Scroll Lines

Mouse Class Definition:

The mouse class inherits from QGraphicsItem. The QGraphicsItem class is the base class for all graphical items in the Graphics View framework, and provides a light-weight foundation for writing your own custom items.

class Mouse : public QGraphicsItem
 {
 public:
     Mouse();

     QRectF boundingRect() const;
     QPainterPath shape() const;
     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                QWidget *widget);

 protected:
     void advance(int step);

 private:
     qreal angle;
     qreal speed;
     qreal mouseEyeDirection;
     QColor color;
 };

When writing a custom graphics item, you must implement QGraphicsItem's two pure virtual public functions: boundingRect(), which returns an estimate of the area painted by the item, and paint(), which implements the actual painting. In addition, we reimplement the shape() and advance(). We reimplement shape() to return an accurate shape of our mouse item; the default implementation simply returns the item's bounding rectangle. We reimplement advance() to handle the animation so it all happens on one update.

Mouse Example:

import java.awt.*;
 import java.awt.event.*;

 public class MouseExample implements WindowListener, MouseMotionListene
   private Frame f;
   private TextField tf;

   public MouseExample(){
     f = new Frame(”Mouse Example”);
     tf = new TextField(30);
   }

   public void launchFrame(){
     Label label = new Label(”Click and drag the mouse”);
     f.add(label, BorderLayout.NORTH);
     f.add(tf, BorderLayout.SOUTH);
     f.addMouseMotionListener(this);
     f.addMouseListener(this);
     f.addWindowListener(this);
     f.setSize(300, 200);
     f.setVisible(true);
   }

   public void mouseDragged (MouseEvent e){
     String s = ”Mouse dragged : X= ”+e . getX()+” Y=”+e.getY();
     tf.setText(s);
   }

   public void mouseEntered(MouseEvent e){
     String s = ”The mouse entered”;
     tf.setText(s);
   }

   public void mouseExited (MouseEvent e){
     String s = ”The mouse has left the building”;
     tf.setText(s);
   }

   public void mousePressed(MouseEvent e){}
   public void mouseReleased(MouseEvent e){}
   public void mouseMoved(MouseEvent e){}
   public void mouseClicked(MouseEvent e){}

   public void windowClosing(WindowEvent e){
     System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     MouseExample me = new MouseExample();
     me.launchFrame();
   }
 }

Java Program: J2SE Event Model in Java

J2SE Event Model:

An event is issued, when the user performs and action at the user interface level like: clicks a mouse or presses a key.

J2SE Event Model Program:

 import java.awt.*;
 import java.awt.event.*;

 public class EventHandle implements WindowListener, ActionListener{
   private Frame f;
   private Button b1, b2, b3;
   private TextField tf;

   public EventHandle(){
     f = new Frame(”Button Handling”);
     b1 = new Button(”YES”);
     b1.setActionCommand(”yes button”);
     b2 = new Button(”NO”);
     b2.setActionCommand (”no button”);
     b3 = new Button (”Clear”);
     b3.setActionCommand (”clear button”);
     tf = new TextField(30);
   }

   public void launchFrame(){
     b1.addActionListener(this);
     b1.setForeground(Color.white);
     b1.setBackground(Color.blue);

     b2.addActionListener(this);
     b2.setForeground(Color.red);
     b2.setBackground(Color.green);

     b3.addActionListener(this);
     b3.setForeground(Color.blue);
     b3.setBackground(Color.yellow);

     tf.setForeground(Color.blue);
     tf.setBackground(Color.white);

     f.setLayout(new FlowLayout());
     f.add(b1);
     f.add(b2);
     f.add(b3);
     f.add(tf);
     f.addWindowListener(this);
     f.setSize(250, 150);
     f.setBackground(Color.red);
     f.setVisible(true);
   }

   public void actionPer formed(ActionEvent e){
     String str;
     if(e.getActionCommand()==” yes button”){
       str = ”You press YES button ”;
       tf.setText(str);
     }
     if(e.getActionCommand()==”no button”){
       str = ”You press NO button”;
       tf.setText(str);
     }
     if(e.getActionCommand()==” clear button”){
       str = ” ”;
       tf.setText(str);
     }
   }

   public void windowClosing(WindowEvent e){
    System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
     EventHandle eh = new EventHandle();
     eh.launchFrame();
   }
 }

Java-Using Abstract Windowing Toolkit (AWT) In Java Applications

Abstract Window Toolkit:

AWT is the basic GUI (Graphics User Interface) used for Java applications and applets. Every GUI component that appears on the screen is a subclass of the abstract class Component or Menu Component. The class Container is an abstract subclass of Component class, which permits other components to be nested inside it. There are two types of containers: Window and Panel. A Window is a free-standing native window on the display that is independent of other containers. There are two important types of Window containers: Frame and Dialog. A Frame is a window with a title and corners that you can resize. A Dialog is a simple window and cannot have a menu bar, you cannot resize it, but you can move it. A Panel must be contained within another Container, or inside a web browser’s window.

Abstract Window Toolkit Example_1:

 import java.awt.*;
 import java.awt.event.*;

 public class FrameWithPanel implements WindowListener{
    private Frame f;
    private Panel p;

    public FrameWithPanel(){
       f = new Frame(”Frame Title”);
       p = new Panel();
    }

    public void launchFrame(){
       f.addWindowListener(this);
       f.setSize(400, 400);
       f.setBackground(Color.red);
       f.setLayout(null);

       p.setSize(150, 150);
       p.setBackground(Color.green);
       f.add(p);
       f.setVisible(true);
   }

   public void windowClosing(WindowEvent e){
      System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconified(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
      FrameWithPanel fp = new FrameWithPanel();
      fp.launchFrame();
   }
 }

Example 2:

 import java.awt.*;
 import java.awt.event.*;

 public class TestMenuBar implements WindowListener, ActionListener{
    private Frame f;
    private MenuBar mb;
    private Menu m1, m2, m3;
    private MenuItem mi1, mi2, mi3, mi4;

    public TestMenuBar(){
       f = new Frame(”MenuBar Example”);
       mb = new MenuBar();
       m1 = new Menu(”File”);
       m2 = new Menu(”Edit”);
       m3 = new Menu(”Help”);
       mi1 = new MenuItem(”New”);
       mi2 = new MenuItem(”Save”);
       mi3 = new MenuItem(”Load”);
       mi4 = new MenuItem(”Quit”);
   }

   public void launchFrame(){
      mi4.addActionListener(this);
      m1.add(mi1);
      m1.add(mi2);
      m1.add(mi3);
      m1.addSeparator();
      m1.add(mi4);

      mb.add(m1);
      mb.add(m2);
      mb.setHelpMenu(m3);
      f.setMenuBar(mb);

      f.addWindowListener(this);
      f.setSize(400, 400);
      f.setBackground(Color.red);
      f.setLayout(null);
      f.setVisible(true);
   }

   public void actionPerformed(ActionEvent e){
      System.exit(0);
   }

   public void windowClosing(WindowEvent e){
      System.exit(0);
   }

   public void windowOpened(WindowEvent e){}
   public void windowIconified(WindowEvent e){}
   public void windowDeiconi fied(WindowEvent e){}
   public void windowClosed(WindowEvent e){}
   public void windowActivated(WindowEvent e){}
   public void windowDeactivated(WindowEvent e){}

   public static void main(String[]args){
      TestMenuBar tmb = new TestMenuBar();
      tmb.launchFrame();
   }
 }


References:

1. Fowler, Amy (1994). "Mixing heavy and light components". Sun Microsystems. Retrieved 17 December 2008.

2. Geertjan, Wielenga (16 December 2008). "A Farewell to Heavyweight/Lightweight Conflicts". Retrieved 17 December 2008.

3. "Bug/RFE fixed in current JDK 6u12 build". Sun Micro systems. 12 December 2008. Retrieved 17 December 2008.

4. Torre, Mario (2 March 2008). "FINAL PROPOSAL: Portable GUI backends". Retrieved 7 September 2008.

5. Kennke, Roman (18 December 2008). "Caciocavallo Architecture Overview". Retrieved 7 September 2008.

6. Kennke, Roman (3 September 2008). "Cacio Swing AWT peers". Retrieved 7 September 2008.

7. "How much has been pushed upstream?". openjdk.java.net. 20 September 2009. Retrieved 7 March 2010. "You don't need anymore those patches, with the latest FontManager push, everything is upstream now, so just use the Cacio repo, it's completely self contained."

8. a b Kennke, Roman (28 July 2011). "JDK7 and Cacio coolness". Retrieved 8 August 2011.

9. Eisserer, Clemens. "HTML5/Canvas backend for Caciocavallo (GNU-Classpath)". Archived from the original on 10 August 2011. Retrieved 8 August 2011.

Java: How to Read a Java String from the contents of a file

I have been using this idiom for some time now. And it seems to be the most wide-spread, at least in the sites I've visited.

Does anyone have a better/different way to Read a Java String from the contents of a file?

private String readFile( String file ) throws IOException {
    BufferedReader reader = new BufferedReader( new FileReader (file));
    String line = null;
    StringBuilder stringBuilder = new StringBuilder();
    String ls = System.getProperty("line.separator");

    while( ( line = reader.readLine() ) != null ) {
        stringBuilder.append( line );
        stringBuilder.append( ls );
    }

    return stringBuilder.toString();
}

Read String from a File Example:-

 import java.io.*;

 public class ReadFile{
   public static void main(String[]args){
      File file = new File(”/home/Parvez/MyJavaBook”, ”MyText.txt”);
      try{
         BufferedReader in = new BufferedReader(new FileReader(file));
         String str = in.readLine();
         while(str != null){
         System.out.println(”Read: ” +str);
         str = in.readLine();
         }
         in.close();
      }catch(FileNotFoundException e1){
         System.out.println(”File not found”);
      }catch(IOException e2){
         System.out.println(”Input/output problem”);
      }
   }
 }

Generation of Source Code:--

/*
Read File in String Using Java Buffered Input Stream Example. This example shows how to read a file content into a Sting object using available and read methods of Java Buffered Input Stream.
*/
    
    import java.io.*;
    
    public class ReadFileInToString {
    
            public static void main(String[] args) {
                  
                    //create file object
                    File file = new File("C://FileIO//ReadFile.txt");
                    BufferedInputStream bin = null;
                  
                    try
                    {
                            //create FileInputStream object
                            FileInputStream fin = new FileInputStream(file);
                          
                            //create object of BufferedInputStream
                            bin = new BufferedInputStream(fin);
                          
                            //create a byte array
                            byte[] contents = new byte[1024];
                          
                            int bytesRead=0;
                            String strFileContents;
                          
                            while( (bytesRead = bin.read(contents)) != -1){
                                  
                                    strFileContents = new String(contents, 0, bytesRead);
                                    System.out.print(strFileContents);
                            }
                          
                    }
                    catch(FileNotFoundException e)
                    {
                            System.out.println("File not found" + e);
                    }
                    catch(IOException ioe)
                    {
                            System.out.println("Exception while reading the file " + ioe);
                    }
                    finally
                    {
                            //close the BufferedInputStream using close method
                            try{
                                    if(bin != null)
                                            bin.close();
                            }catch(IOException ioe)
                            {
                                    System.out.println("Error while closing the stream :"
    + ioe);
                            }
                          
                    }
            }
          
    }
    
    
/*
Output would be This file is for demonstration of how to read a file into String using Java Buffered Input Stream.
*/

About Java | Write String to File using JavaScript Program

Write String to a File:

I am a beginner Java programmer attempting to make a simple text editor. I have the text from the text field in a String variable called "text".

How can I save the contents of the "text" variable to a text file?

String File Example 1:

import java.i o.*;

 public class WriteFile{
   public static void main(String[]args){
      File file = new File (”/home/Parvez/MyJavaBook” , ”MyText.txt”);
      try{
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader in = new Buf feredReader(isr);
         PrintWriter out = new PrintWriter(new FileWriter(file));
         System.out.println (”Write String: ”);
         String str = in.readLine();
         out.println(str);
         in.close();
         out.close();
      }catch(IOException e){
         e.printStackTrac e ();
      }
   }
 }

String File Example 2:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class WriteToFileExample
{
  public static void main(String[] args)
  {
    try
    {
      // Here we'll write our data into a file called
      // sample.txt, this is the output.
      File file = new File("sample.txt");
      // We'll write the string below into the file
      String data = "Learning Java Programming";

      // To write a file called the writeStringToFile
      // method which require you to pass the file and
      // the data to be written.
      FileUtils.writeStringToFile(file, data);
    } catch (IOException e)
    {
      e.printStackTrace();
    }
  }
}

String File Example 3:

It's a simple example to write String to text file using Java code. Please note that you need the right to write in the target file.

package javafile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class WriteStringToFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        FileWriter fileWriter = null;
        try {
            String content = "Hello! Java-Buddy :)";
            File newTextFile = new File("C:/test/test.txt");
            fileWriter = new FileWriter(newTextFile);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

100 Java - Java Read File Line by Line in Java Program

Introduction:

This article shows how to cache files in Java in order to increase application performance. It discusses an algorithm for caching the file, a data structure for holding the cached content and a cache API for storing cached files.

File in Java:

To access a physical file we have to create a File object, which contains the address and name of the file. The FileReader class uses to read characters from a file and the FileWriter class uses to write characters to a file. The PrintWriter class is used the print() and println() methods.

Caching Files in Java:

Reading files from the disk can be slow, especially when an application reads the same file many times. Caching solves this problem by keeping frequently accessed files in memory. This allows the application to read the content of the from the fast local memory instead of the slow hard drive. Design for caching a file in Java includes three elements:

    1. An algorithm for caching the file
    2. A data structure for holding the cached content
    3. A cache API for storing cached files

Algorithm for Caching Files:-

A general algorithm for caching a file must account for file modifications and consists of the following steps:

    1. Get a value from the cache using a fully qualified file path as a key.
    2. If a key is not found, read the file content and put it to the cache.
    3. If the key is found, check if a timestamp of the cached content matches the file timestamp.
    4. If the timestamps are equal, return the cached content.
    5. If the timestamps are not equal, refresh the cache by reading the file and putting it into the cache.

Java Code for Caching Files:-

This article assumes that the file being cached is a text file. A code fragment below implements the caching algorithm for text files:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import cacheonix.Cacheonix;
import cacheonix.cache.Cache;
import com.cacheonix.examples.cache.file.cache.data.grid.TextFile;

/**
 * An application demonstrating an application-level file cache.
 */
public class ApplicationFileCacheExample {

   /**
    * Gets a file content from the cache ant prints it in the standard output.
    *
    * @param args arguments
    * @throws IOException if an I/O error occured.
    */
   public static void main(String[] args) throws IOException {

      // Replace the file name with an actual file name
      String pathName = "test.file.txt";

      ApplicationFileCacheExample fileCacheExample = new ApplicationFileCacheExample();
      String fileFromCache = fileCacheExample.getFileFromCache(pathName);
      System.out.print("File content from cache: " + fileFromCache);
   }

   /**
    * Retrieves a file from a cache. Puts it into the cache if it's not cached yet.
    *
    * This method demonstrates a typical flow an application must follow to cache a file
    * and to get it from the cache. As you can see, the application is pretty involved
    * in maintaining the cache. It must read the file, check the the timestamps and update
    * the cache if its content is stale.
    *
    * @param pathName a file path name.
    * @return a cached file content or null if file not found
    * @throws IOException if an I/O error occurred.
    */

   public String getFileFromCache(String pathName) throws IOException {

      // Get cache
      Cacheonix cacheonix = Cacheonix.getInstance();

      Cache<String, TextFile> cache = cacheonix.getCache("application.file.cache");

      // Check if file exists
      File file = new File(pathName);
      if (!file.exists()) {

         // Invalidate cache
         cache.remove(pathName);

         // Return null (not found)
         return null;
      }

      // Get the file from the cache
      TextFile textFile = cache.get(pathName);

      // Check if the cached file exists
      if (textFile == null) {

         // Not found in the cache, put in the cache

         textFile = readFile(file);

         cache.put(pathName, textFile);
      } else {

         // Found in cache, check the modification time stamp

         if (textFile.getLastModified() != file.lastModified()) {

            // Update cache

            textFile = readFile(file);

            cache.put(pathName, textFile);
         }
      }

      return textFile.getContent();
   }

   /**
    * Reads a file into a new TextFile object.
    *
    * @param file the file to read from.
    * @return a new TextFile object.
    * @throws IOException if an I/O error occurred.
    */

   private static TextFile readFile(File file) throws IOException {

      // Read the file content into a StringBuilder
      char[] buffer = new char[1000];
      FileReader fileReader = new FileReader(file);
      StringBuilder fileContent = new StringBuilder((int) file.length());

      for (int bytesRead = fileReader.read(buffer); bytesRead != -1; ) {
         fileContent.append(buffer, 0, bytesRead);
      }

      // Close the reader
      fileReader.close();

      // Create CachedTextFile object
      TextFile textFile = new TextFile();
      textFile.setContent(fileContent.toString());
      textFile.setLastModified(file.lastModified());

      // Return the result
      return textFile;
   }
}

Related Tags for Java Read File Line by Line-Java:

java, c, string, mac, com, file, unicode, orm, data, form, utf-8, application, strings, input, io, types, format, output, streams, type, stream, system, number, read, transform, write, open, app, if, for, primitive, transformation, company, to, information, ci, ndepend, e, il, safe, it, doc, can, machine, li, mit, put, specification, use, pe, modification, im, from, in, mod, utf, rm, info, cs, m, nt, out, tr, nic, min, ca, min, nic, j, ad, es, spec, td, em, end, pen, ico, me, modi, pp, pan, cat, fs, do, sys, rel, s, sp, ee, at, any, late, is, ha, inf, iv, pre, erl, erl, ea, and, ar, cod, code, str, specific, tf, repr, sa, saf, sli, va, uses, underlying, ucs, s, s, ri, ring, th, av, st, chi, 6, ati, ap, af, hat, fe, inform, informat, ica, ica, pl, pr, mina, mi, nd, ode, on, om, o, np