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");
}
}
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();
}
}
}
Converting byte array to base64 string in java
public class ImageProcessing {
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("/Users/Lakshman/Pictures/image.jpeg");
try {
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = encodeImage(imageData);
// Converting a Base64 String into Image byte array
byte[] imageByteArray = decodeImage(imageDataString);
// Write a image byte array into file system
FileOutputStream imageOutFile = new FileOutputStream(
"/Users/Lakshman/Pictures/image.jpeg");
imageOutFile.write(imageByteArray);
imageInFile.close();
imageOutFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
}
/**
* Encodes the byte array into base64 string
*
* @param imageByteArray - byte array
* @return String a {@link java.lang.String}
*/
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
/**
* Decodes the base64 string into byte array
*
* @param imageDataString - a {@link java.lang.String}
* @return byte array
*/
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
}
Thursday, 10 January 2013
Upload an image into the database in java
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" %>
<%@ page import="java.awt.image.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.File"%>
<%@ page import="javax.imageio.ImageIO"%>
<%@ page import="java.awt.image.BufferedImage,java.util.*"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.util.*,com.oreilly.servlet.MultipartRequest"%>
<%
/* The Following Code is Used To Insert An Image Into Database */
String filename="";
try
{
//Download com.oreilly package
MultipartRequest multi= new MultipartRequest(request,".",5*1024*1024);
Enumeration files=multi.getFileNames();
File f=null;
while(files.hasMoreElements())
{
String name=(String)files.nextElement();
filename=multi.getFilesystemName(name);
String type=multi.getContentType(name);
f=multi.getFile(name);
System.out.println("The File is "+f);
}
Connection con=null;
String userName="root";
String password = "veradis";
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample",userName,password);
Statement stmt = con.createStatement();
InputStream is = new FileInputStream(f);
byte b[]=new byte[is.available()];
is.read(b);
int flag=0;
try
{
String sql = "INSERT into tbl_image(image) values('" + b + "')";
System.out.println(sql);
stmt.execute(sql);
flag=1;
}
catch(Exception e)
{
System.out.println("SQL Exception : " + e);
}
if(flag==1)
{
System.out.println("Query Executed Successfully");
}
stmt.close();
}
catch(Exception e)
{
System.out.println(e);
}
out.println("The Image is Added into Database");
%>
Retrieve and display an image from and to the database
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ page language="java" %> <%@ page import="java.awt.image.*"%> <%@ page import="java.io.*"%> <%@ page import="java.sql.*"%> <%@ page import="javax.servlet.*"%> <%@ page import="javax.servlet.http.*"%> <%@ page import="java.io.File"%> <%@ page import="javax.imageio.ImageIO"%> <%@ page import="java.awt.image.BufferedImage,java.util.*"%> <%@ page import="java.awt.*"%>JSP Page <% try { javax.servlet.http.HttpServletResponse res=null;; int returnValue = 0; Connection conn = null; Statement stmt = null; ResultSet rs = null; InputStream in = null; OutputStream os = null; Blob blob = null; String text; text=request.getParameter("text"); Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","password"); final String query = "SELECT image FROM tablename"; conn.setAutoCommit(false); stmt = conn.createStatement(); rs = stmt.executeQuery(query); int i=1; if(rs.next()) { String len1 = rs.getString("image"); int len = len1.length(); byte [] b = new byte[len]; in = rs.getBinaryStream("image"); int index = in.read(b, 0, len); OutputStream outImej = new FileOutputStream("C:/Documents and Settings/Desktop/photo/img"+i+".JPG"); while (index != -1) { outImej.write(b, 0, index); index = in.read(b, 0, len); System.out.println(index); System.out.println(outImej); } outImej.close(); i++; } else { returnValue = 1; } } catch(Exception e) { out.println(e); } %>
Subscribe to:
Comments (Atom)