29 Şubat 2012 Çarşamba

Java - Finding length of a result set

ResultSet res = stat.executeQuery();
res.last();
int n = res.getRow(); // no. of rows in result

28 Şubat 2012 Salı

Java - TCP File Transfer

**********CLIENT*********

public static void main(String[] args) {
byte[] aByte = new byte[1];
int bytesRead;

Socket clientSocket = null;
InputStream is = null;

try {
clientSocket = new Socket("127.0.0.1", 3248);
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}

ByteArrayOutputStream baos = new ByteArrayOutputStream();

if (is != null) {

FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("out.txt");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);

do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);

bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}

}

*********SERVER**************

public static void main(String[] args) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;

try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}

if (outToClient != null) {
File myFile = new File("in.txt");
byte[] mybytearray = new byte[(int) myFile.length()];

FileInputStream fis = null;

try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);

try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();

// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}

}

Java TCP Client - Server

//***Client*******//

public static void main(String[] args) {
Socket socket;

InetAddress address;

DataOutputStream os;

try {
address = InetAddress.getByName("127.0.0.1");
socket = new Socket(address, 20000);
os = new DataOutputStream(socket.getOutputStream());
os.writeBytes("helllo");

os.close();
socket.close();

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
//***Server*******//
public static void main(String[] args) {
ServerSocket serverSocket;

InetAddress serverAddress;

DataInputStream is;

try {
serverAddress = InetAddress.getByName("127.0.0.1");

serverSocket = new ServerSocket(20000, 10, serverAddress);

Socket client = serverSocket.accept();

is = new DataInputStream(client.getInputStream());

String str = is.readLine();

System.out.print(str);

is.close();
client.close();
serverSocket.close();

} catch (IOException e) {

e.printStackTrace();
}

}

27 Şubat 2012 Pazartesi

Java - Open folder or directory using java

import java.util.*;
import java.io.*;
import java.awt.Desktop;

class OpenFolderInJava{

public static void main(String[] arg){
String path = "."; // path to the directory to be opened
File file = new File("C:\\");
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
try {
desktop.open(file);
}
catch (IOException e){
}
}
}

25 Şubat 2012 Cumartesi

JavaMail – GMail via SSL

To send an email using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

You can download latest version of JavaMail from Java's standard website.

You can download latest version of JAF from Java's standard website.


package com.mkyong.common;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

22 Şubat 2012 Çarşamba

Open existing project in Eclipse

Use File > Import and select General > Existing Projects into Workspace.
Click next and then browse to the directory contain the project directory.

20 Şubat 2012 Pazartesi

Setting the JAVA_HOME Variable

Once you have identified the JRE installation path:

1. Right-click the My Computer icon on your desktop and select Properties.
2. Click the Advanced tab.
3. Click the Environment Variables button.
4. Under System Variables, click New.
5. Enter the variable name as JAVA_HOME.
6. Enter the variable value as the installation path for the Java Development Kit.
7. If your Java installation directory has a space in its path name, you should use the shortened path name
(e.g. C:\Progra~1\Java\jre6) in the environment variable instead.
8. Click OK.
9. Click Apply Changes.
10. Restart Windows. (This is not always necessary, but it often prevents problems.)
11. If you are running the Confluence EAR/WAR distribution, rather than the regular Confluence distribution, you may need to restart your application server.

12 Şubat 2012 Pazar

Java - Write Text File

FileWriter fWriter = null;
BufferedWriter writer = null;

try {
fWriter = new FileWriter("fileName");
writer = new BufferedWriter(fWriter);

//WRITES 1 LINE TO FILE AND CHANGES LINE
writer.write("This line is written");
writer.newLine();


writer.close();
}
catch (Exception e) {

}

10 Şubat 2012 Cuma

Java - Read Text File

This code will read the MyFile.txt and print its content on the console. It reads the file line by line in the form of DataInputStream.


package MyProject

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class FileInput {

public static void main(String[] args) {

File file = new File("C:\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
fis = new FileInputStream(file);

// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {

// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}

// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java - setDefaultCloseOperation

Bir frame kapatılınca parent frame de kapatılacak mı...
Bunu şu şekilde set edebiliyoruz:

public void run() {
    KayıtFrame kf = new KayıtFrame();
    kf.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    kf.setVisible(true);
}

8 Şubat 2012 Çarşamba

Java - Folder Chooser

com.jidesoft.swing.FolderChooser kullanabilmek için jar'ını indirmeniz lazım.
İndir

FolderChooser chooser = new FolderChooser();
int returnVal = chooser.showOpenDialog(null);
if(returnVal == FolderChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getAbsolutePath());
}

Database'de Türkçe karakter sorunu

Connection url'inize sonuna şu satırı eklemeniz yeterli.

"?characterSetResults=UTF-8&characterEncoding=UTF-8&useUnicode=yes"

String conUrl = "jdbc:mysql://127.0.0.1:3306/db_drive?characterSetResults=UTF-8&characterEncoding=UTF-8&useUnicode=yes";

7 Şubat 2012 Salı

Java - Connect to MySQL with JDBC

Jdbc'yi kullanabilmek için önce connector download etmemiz lazım:

Connector İndir

Bir dosyaya unzip yaptıktan sonra, Eclipse'de projeye sağ tıklayıp build path diyoruz.
Jar dosyasını seçiyoruz. Böylelikle Referenced Libraries'e eklenmiş oluyor.






















Basit bir database'e bağlanma kodu:

Class.forName("com.mysql.jdbc.Driver").newInstance();

//localhost yerine bağlanmak istediğiniz db'in ip'sini
//eğer localde çalışıyorsanız ve localhost çalışmıyorsa 127.0.0.1' i deneyin
String url = "jdbc:mysql://localhost/databaseName";

//MySQL'in kullanici adı ve şifresini girin
//default windows'da username = root, password=""
conn = DriverManager.getConnection(url, "username", "password");

//connection'ı yarattıktan sonra istediğiniz işlemler query'lilerle yapılcak

String query = "SELECT COF_NAME, PRICE FROM COFFEES";
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}

4 Şubat 2012 Cumartesi

Getting Apache to run on port 80 on Windows 7

Solution:

1) Launch RegEdit:

2) Go to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP

3) Add a new DWORD (32-bit) value

4) Name it ‘NoRun’ not including the quotes

5) Double click the new property

6) In the Value data field type ’1′ not including quotes and click OK

7) Re-boot your computer

You should now find that Apache will start on port 80!

link


3 Şubat 2012 Cuma

Fast and Effective GUI Building in Java

Hızlı ve güzel bir şekilde java'da gui tasarlamak için Netbeans en ideali. Design kısmından sürükle bıraklarla istediğiniz formları, login frameleri tasarlamak çok kolay.

Referans: link


2 Şubat 2012 Perşembe

Watching a Directory for Changes

örnek kod

Referans : oracle

Örneğin bir dosyada bir değişiklik yapılıp yapılmadığını kontrol etmek istiyorsunuz.
Değişiklik var mı? Değişiklik var mı? diye sürekli sormaktansa (polling) bir değişiklik olunca o bize söylesin.
Yeni bir dosya yaratıldı, silindi veya değişti diye.

* ENTRY_CREATE – A directory entry is created.
* ENTRY_DELETE – A directory entry is deleted.
* ENTRY_MODIFY – A directory entry is modified.
* OVERFLOW – Indicates that events might have been lost or discarded. You do not have to register for the OVERFLOW event to receive it.


How to Add JARs to Project Build Paths in Eclipse (Java)

1. Copy the JARs you'll be using to your project.

       1. Create a new folder named lib in your project folder.
       This stands for "libraries" and will contain all the JARs you'll be using for that project.

      2. Copy the JARs you need to lib.

       3. Refresh your project by right clicking the project name and selecting Refresh.
       The lib folder will now be visible in Eclipse with the JARs inside.

2. Expand lib in Eclipse and select all the JARs you need.

3. Right-click the JARs and navigate to Build Path.

4. Select Add to Build Path. The JARs will disappear from lib and reappear in Referenced Libraries.



Daha ayrıntılı bilgi : bu linki ziyaret edebilirsiniz