Setting Multi-Line label on the Button

Objective:to set the multi line label on the button in Java Swing Applications.

This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you run the program it will look like following image:

Multiline Labe of the Button

Setting Multi-Line label on the Button

This section shows you how to set the multi line label on the button in Java Swing Applications.

This program uses html class from javax.swing.text.html*; package and then breaks the text label of the button into two lines. If you run the program it will look like following image:

Multiline Labe of the Button

HTML:

This is the class from the javax.swing.text.html.*; package of Java. This class provides the facility to use the html tags in java application for texts. There are tag and
tag have been used in this program. Tags of html are used with the string which is the label of the button.

Here is the code of the program:


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

public class MultilineLabelButton{
public static void main(String[] args){
JFrame frame = new JFrame("Multiline Label for Button");
String lbl = "" + "This label" + "
" + "is in two lines" + "";
Panel panel = new Panel();
JButton button = new JButton(lbl);
panel.add(button);
// frame.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Various date format conversions


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GeneralUtil {

//Date Time Util
public static Timestamp getTimeStamp(String date) throws ParseException {
String DATE_FORMAT = "MM-dd-yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date today = dateFormat.parse(date);
Timestamp t1 = new Timestamp(today.getTime());
return t1;
}

public static String getCurrentDateTime(String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
Date date = new Date();
return dateFormat.format(date);
}

public static String getDateMMDDYYY(Timestamp timestamp) {
String dateStr = "";

dateStr = timestamp.toString().substring(0, 10);
return dateStr;
}

public static String getDateFromDBStringMMDDYYYY(String theDate) {
String strOutDt = "";
try {
Date dtTmp = new SimpleDateFormat("yyyy-MM-dd").parse(theDate);
strOutDt = new SimpleDateFormat("MM-dd-yyyy").format(dtTmp);
} catch (ParseException pe) {
}
return strOutDt;
}

// public static void main(String[] args) throws ParseException {
//
public static String getDateFromTimeStamp(Timestamp t) {
String result = "";
try {
Timestamp dateTime = (Timestamp) t;

SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
result = dateFormat.format(dateTime);
return result;
} catch (Exception exception) {
}
return result;

}

public static String getDBDateFormat(String dateStr) {
String result = "";
try {
Date dtTmp = new SimpleDateFormat("MM-dd-yyyy").parse(dateStr);
result = new SimpleDateFormat("yyyy-MM-dd").format(dtTmp);
return result;
} catch (Exception exception) {
}
return result;

}

public static double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
//End Date Time Util

public static void main(String[] args) throws ParseException {
String str = "11-24-2010";

}
}

Transfer a file via Socket

A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!

First a server module.


import java.net.*;
import java.io.*;

public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");

Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);

// sendfile
File myFile = new File ("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}

The client module


import java.net.*;
import java.io.*;

public class FileClient{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");

// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source-copy.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}

Create/Delete Directory ,File

In the section of Java Tutorial you will learn how to create directory using java program. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.

Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.

Here is the code for creating directory and all non-existing ancestor directories:


import java.io.*;
class CreateDirectory
{
public static void main(String args[])
{
try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";

// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");
}

// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");
}

}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

This example illustrates how to delete the specified file or directory after checking weather the file exists or not. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames.

Explanation

This program deletes the specified file if that exists. We will be declaring a function called deletefile which deletes the specified directory or file.

deletefile(String file)

The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(file);

and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.

delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Returns:
true if and only if the file or directory is successfully deleted; false otherwise

Code of the Program :


import java.io.*;

public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}else{
System.out.println("File deleted.");
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Java – Copying one file to another

Objective:to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:

1. An optional system-dependent prefix string,
such as a disk-drive specifier, “/” for the UNIX root directory, or “\\” for a Win32 UNC pathname, and
2. A sequence of zero or more string names.

Explanation

This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.

copyfile(String srFile, String dtFile)

The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(srFile);
File f2 = new File(dtFile);

and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.

// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);

Code of the Program :


import java.io.*;

public class CopyFile{
private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Java Write To File

Objective: to write java program to write to a file. We will use the class FileWriter and BufferedWriter to write to a file.

Class FileWriter:

The FileWriter is a class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter:

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:


import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}