import java.io.*;
public class Vcard{
public static void main(String[] args) throws IOException{
File f=new File("contact.vcf");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="BEGIN:VCARD\n" +
"VERSION:4.0\n" +
"N:Gump;Forrest;;;\n" +
"FN:Forrest Gump\n"+
"ORG:Bubba Gump Shrimp Co.\n"+
"TITLE:Shrimp Man\n"+
"TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212\n"+
"TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212\n"+
"EMAIL:forrestgump@example.com\n"+
"REV:20080424T195243Z\n"+
"END:VCARD";
fop.write(str.getBytes());
//Now read the content of the vCard after writing data into it
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(new FileReader("contact.vcf"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
//close the output stream and buffer reader
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file does not exist");
}
}
Java blog
Thursday, 7 February 2013
How to create a vCard in Java
Sunday, 27 January 2013
Get user input using java swing and write to text file
import java.io.*;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class ClientList
{
public static void main (String args[]) throws IOException
{
// Main class ClientList creates Clients.txt file that is to be opened up and appended whenever clients are to be added
FileWriter outFile = new FileWriter("Clients.txt");
BufferedWriter outStream = new BufferedWriter(outFile);
String outString = "Client Listing";
outStream.write(outString);
outStream.newLine();
outStream.close();
System.out.println("Clients.txt is created\n");
// "Primitive" menu asks user what he/she wants to do and accepts commands via keyboard scanner
Scanner menu = new Scanner(System.in);
System.out.println("Welcome to ClientList");
System.out.println();
System.out.println("To add clients to the file, enter 1");
System.out.println("To open file and view its contents, enter 2");
// System.out.println("To search for a client in the file, enter 3");
int command = menu.nextInt();
switch (command)
{
case 1: Clients client = new Clients();
client.enterData();
break;
case 2: Clients client2 = new Clients();
client2.getClients();
break;
// case 3: Clients client = new Clients();
// client.searchClients();
// break;
default: System.out.println("Doesn't exist!");
System.out.print("Enter a valid number ===> ");
int l = menu.nextInt();
break;
}
}
}
class Clients
{
// Initializing variables for client data
String firstName;
String lastName;
String age;
String height;
String weight;
String startDate;
String phNum;
public void enterData() throws IOException
{
// Initializing boolean variable isValid to check the number of clients user inputs
// and make sure it really IS a number
boolean isValid = false;
String number;
// Ask user how many clients he/she wishes to enter data for
do
{
number = JOptionPane.showInputDialog("Enter the number of clients you wish to save:");
// Loop to check what the user entered against the allowed charcters (only numbers between 0 and 9 allowed)
if (number.matches("[0-9]*"))
{
isValid = true;
}
else
{
isValid = false;
}
}
while (isValid != true); // Keeps prompting user for a number until a valid number between 0 and 9 is entered
// Finally, parse String number and change to an integer for use in data input loop
int numOfClients = Integer.parseInt(number);
// Data input prompts are put into a loop that repeats until data for all clients is entered
for (int k = 0; k
Thursday, 24 January 2013
How to iterate throught a Map
//Declare a map object MapmapObj = new HashMap (); //iterate through the map objects elements one by one for (Map.Entry entry : mapObj.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
Friday, 18 January 2013
how to convert Byte[] array to String in Java
public class ByteToString
{
public static void main(String[] args) {
String example = "This is an example";
byte[] bytes = example.getBytes();
System.out.println("Text : " + example);
System.out.println("Text in Byte Format] : " + bytes);
System.out.println("Text in Byte Format] : " + bytes.toString());
String s = new String(bytes);
System.out.println("Text converted : " + s);
}
}
Java program to insert image into database
This is a simple java program used to inject an image into the mysql database:
import java.sql.*;
import java.io.*;
public class insertImg{
public static void main(String[] args) {
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "hibernatetutorial";
String userName = "root";
String password = "root";
Connection con = null;
try {
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("images.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into Image values(?,?,?)");
pre.setInt(1,5);
pre.setString(2,"Durga");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
con.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Wednesday, 16 January 2013
Retrieve and Store BLOB from/to MySQL in Java awt
This post shows you how to insert an image into MySQL database through Java
Step 1 : Open MySQL client
Step 2 : Execute the following query
CREATE TABLE IF NOT EXISTS `image` ( IMG blob, IMG_ID int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`IMG_ID`) )Source code -----------
import java.awt.event.ActionEvent;
import java.sql.*;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author mustaq
*/
public class ImagePanel extends JPanel implements ActionListener {
JButton browse;
Connection con = null;
public ImagePanel() {
con = this.getConnection();
browse = new JButton("Browse");
browse.addActionListener(this);
this.add(browse);
}
public Connection getConnection() {
try {
// Creating connection to DB
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/image";
Connection c = DriverManager.getConnection(url,"root","");
return c;
}
catch(Exception ex) {
System.out.println(ex.getMessage());
return null;
}
}
public void imageWrite(File file) {
try {
FileInputStream io = new FileInputStream(file);
String query = "insert into image(IMG) values(?)";
java.sql.PreparedStatement stmt = con.prepareStatement(query);
stmt.setBinaryStream(1, (InputStream)io,(int)file.length());
stmt.executeUpdate();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
public BufferedImage getImageById(int id) {
String query = "select IMG from image where IMG_ID = ?";
BufferedImage buffimg = null;
try {
PreparedStatement stmt = con.prepareStatement(query);
stmt.setInt(1,id);
ResultSet result = stmt.executeQuery();
result.next();
InputStream img = result.getBinaryStream(1); // reading image as InputStream
buffimg= ImageIO.read(img); // decoding the inputstream as BufferedImage
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
return buffimg;
}
@Override
public void paint(Graphics g) {
BufferedImage img = this.getImageById(5) ; // pass valid IMG_ID
if(img != null)
g.drawImage(img, 70, 20, this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("ImagePanel Demo");
ImagePanel imgPanel = new ImagePanel();
frame.setVisible(true);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(imgPanel);
}
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
File file = null;
if(returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile(); // path to image
this.imageWrite(file); // inserting image into database
JOptionPane.showMessageDialog(this, "Image inserted.", "ImageDemo", JOptionPane.PLAIN_MESSAGE);
this.repaint();
}
}
}
Subscribe to:
Comments (Atom)