顯示具有 [Java] 標籤的文章。 顯示所有文章
顯示具有 [Java] 標籤的文章。 顯示所有文章

2009年3月7日 星期六

[轉][Java]Gmail- POP3 & SMTP

Gmail目前已經啟用了POP3和SMTP服務,
與其他郵箱不同的是Gmail提供的POP3和SMTP是使用安全套接字層SSL的,
因此常規的JavaMail程序是無法收發郵件的,
下面是使用JavaMail如何收取Gmail郵件以及發送郵件的代碼:

1. 郵件收取

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;

/**
* 用於收取Gmail郵件
* @author Winter Lau
*/
public class GmailFetch {

public static void main(String argv[]) throws Exception {

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");

//以下步驟跟一般的JavaMail操作相同
Session session = Session.getDefaultInstance(props,null);

//請將紅色部分對應替換成你的郵箱帳號和密碼
URLName urln = new URLName("pop3","pop.gmail.com",995,null,
"[郵箱帳號]", "[郵箱密碼]");
Store store = session.getStore(urln);
Folder inbox = null;
try {
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
Message[] messages = inbox.getMessages();
inbox.fetch(messages, profile);
System.out.println("收件箱的郵件數:" + messages.length);
for (int i = 0; i < messages.length; i++) {
//郵件發送者
String from = decodeText(messages[i].getFrom()[0].toString());
InternetAddress ia = new InternetAddress(from);
System.out.println("FROM:" + ia.getPersonal()+'('+ia.getAddress()+')');
//郵件標題
System.out.println("TITLE:" + messages[i].getSubject());
//郵件大小
System.out.println("SIZE:" + messages[i].getSize());
//郵件發送時間
System.out.println("DATE:" + messages[i].getSentDate());
}
} finally {
try {
inbox.close(false);
} catch (Exception e) {}
try {
store.close();
} catch (Exception e) {}
}
}

protected static String decodeText(String text)
throws UnsupportedEncodingException {
if (text == null)
return null;
if (text.startsWith("=?GB") || text.startsWith("=?gb"))
text = MimeUtility.decodeText(text);
else
text = new String(text.getBytes("ISO8859_1"));
return text;
}
}


2. 發送郵件

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
* 使用Gmail發送郵件
* @author Winter Lau
*/
public class GmailSender {

public static void main(String[] args) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "[郵箱帳號]";
final String password = "[郵箱密碼]";
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});

// -- Create a new message --
Message msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@mo168.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[收件人地址]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);

System.out.println("Message sent.");
}
}


[REF]:http://balafish.blogspot.com/2007/10/javamailgmailssl.html

2008年11月10日 星期一

[Java]如何讓JTextArea內容總顯示最後一筆[已解決]


public void myChange(String change) {
String tmp = jTextArea1.getText();
tmp = tmp.concat(change + "\n\r");
jTextArea1.setText(tmp);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jScrollPane1.getVerticalScrollBar().setValue(jScrollPane1.getVerticalScrollBar().getMaximum());
}
});
}

2008年11月9日 星期日

[Java]An Efficient Stream Copier


public class StreamCopier {

public static void main(String[] args) {
try {
copy(System.in, System.out);
} catch (IOException e) {
System.out.println(e);
}

}

public static void copy(InputStream in, OutputStream out) throws IOException {

/*複製過程中,不允許其他執行緒讀取輸入串流或寫入輸出串流*/
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
}
}
}
}

2008年10月31日 星期五

[Java][O'REILLY] Java I/O技術(note) - part1

Java的大部分I/O形式分兩種:

1.byte & number,由輸入輸出的stream處理。
2.character 與 text,由reader 和 writer 處理。
stream:
是一連串又順序,但長度尚未判斷出來的位元組。

input stream:

把位元組從某個一般性的外界來源搬進Java程式。

output stream:

把位元組從Java程式內部搬到某一般性的外部目標,在某些情況下,串流能把位元組從Java程式的某部分搬到另一部分。

flush():

一般來說,緩衝區未滿之前,資料是不會被送出去,但如果你希望對方能儘快收到資料(或其他原因),可以呼叫flush()強制出清緩衝區,不管緩衝區是否滿了。
請注意,flush()並不會出清作業系統或硬體的緩衝區。輸出串流的緩衝區,與硬體或OS的緩衝區是兩回事。若要出清這類緩衝區,可以考慮使用FileDescriptor類別的sync()。

除非有特殊用意,否則我們不會刻意出清緩衝區。因為當串流關閉時,緩衝區內的的資料會被自動寫到目的地,串流會在程式結束時,或你使用close()方法時被關閉。


什麼時候會用到flush():

1.若你的程式大打算透過網路傳送一堆資料,你應該週期性的出清緩衝區,確定資料已經送出。
2.在出錯一個會當掉的程式時。照理說,所有輸出串流在緩衝區被填滿時會自動出清,這是在程式能正常結束的前提下,這沒有問題。但如果程式不正常結束,則緩衝區就會殘留資料。此時除非每次寫入資料後去可以呼叫flush(),否則就無法依據輸出的資料來判斷程式當掉的地方,因為程式可能出錯之後繼續執行一段時間。
3.System.out、System.err和某些列印串流(print stream),在每次呼叫println()之後,以及每次寫入的字串遇到'\n'換行字元之後,緩衝區會被自動出清。你可以在PrintStream建構式中,設定是否啟動自動出清。

system.out:

system.out是printStream的實體,若你在關閉system.out之後試圖寫入它,他並不會對出IOException,只不過要寫的東西不會出現吧了。這是因為system.out的使用率太頻繁,因此Sun決定讓它吃掉所有IOException,免得每次都要用try/catch包著它。因此在所有串流中System.out算是一種特例。

[Java]關於FilenameFilter的使用



import java.io.FilenameFilter;
import java.io.File;

class HTMLFilter implements FilenameFilter {

public boolean accept(File dir, String name) {
return (name.endsWith(".html"));
}
}

class Main {

public static void main(String[] args) {
String dir = ".";
if (args.length == 1) {
dir = args[0];
}

File f1 = new File(dir);
int i;
String[] ls;
FilenameFilter filter = new HTMLFilter();
System.out.println("HTML Files: ");
for (ls = f1.list(filter), i = 0;
ls != null && i < ls.length;
System.out.println("\t" + ls[i++])) {
;
}
}
}


[REF]http://home.tiscali.nl/~bmc88/java/sbook/0128.html

2008年10月30日 星期四

[Java]動態生成JButton 問題究竟出在哪裡?(已解決)

問題究竟出在哪裡?

import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

JFrame myFrame;
JPanel myPanel;
JButton btn[];
Toolkit toolkit = Toolkit.getDefaultToolkit();

Main() {
myPanel = new JPanel();


for (int i = 0; i < 5; i++) {
btn[i] = new JButton();
myPanel.add(btn[i]);
}
add(myPanel);
}

public static void main(String argv[]) {
Main app = new Main();
app.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {
System.out.println("Frame closing...");
System.exit(0);
}
});
app.setVisible(true);
app.repaint();
}
}


原來是這裡忘了初始= =

JButton btn[];

改成

JButton btn[] = new JButton[5];

[Java]有關Acegi

感覺很像是好東西,先收起來再說^^
點我下載

[REF]http://www.javaworld.com.tw/jute/post/view?bid=43&id=243119&tpg=1&ppg=1&sty=1&age=0#243119

2008年10月24日 星期五

[Java] [Fw]如何讓netbean的Project File匯入jar檔(以iText產生Pdf為例)

以下詳細的介紹用Netbean實作的整個過程
(以下教導如何讓netbean的Project File匯入jar檔):
Step1:


Step2:


Step3:



Step4:





Step5:



經過上述的步驟,就已經成功將Jar檔加入這個Project了。

接下來開一個Class檔,
將以下程式call進去,再Compile + Run...

/**
* HelloWorld.java
*/
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello World");

// 創建一個Document對象
Document document = new Document();

try {

// 生成名為 HelloWorld.pdf 的文檔
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));

// 添加PDF文檔的一些信息
document.addTitle("Hello World example");
document.addAuthor("Bruno Lowagie");
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello World, step 3, metadata");
document.addCreator("My program using iText");

// 打開文檔,將要寫入內容
document.open();

// 插入一個段落
document.add(new Paragraph("Hello World!"));

} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

// 關閉打開的文檔
document.close();
}
}

完成第一個pdf的產生。

[Java][Fw] Java iText 動態 生成 PDF 文檔表格中文問題

無法查看此摘要。請 按這裡查看文章。

2008年10月20日 星期一

[Java][Fw]Java讀寫cookie

Java讀寫cookie

/*
* 寫cookie
*/
Cookie namecookie = new Cookie("name",name);
Cookie passwordcookie = new Cookie("password",password);
Cookie optioncookie = new Cookie("option","1");

//生命週期
namecookie.setMaxAge(60*60*24*365);
passwordcookie.setMaxAge(60*60*24*365);
optioncookie.setMaxAge(60*60*24*365);

response.addCookie(namecookie);
response.addCookie(passwordcookie);
response.addCookie(optioncookie);

/*
* 讀cookie
*/
Cookie[] cookies = request.getCookies();
if(cookies!=null)
{
String name = "";
String password = "";
String option = "";
for (int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if(c.getName().equalsIgnoreCase("name"))
{
name = c.getValue();
}
else if(c.getName().equalsIgnoreCase("password"))
{
password = c.getValue();
}
else if(c.getName().equalsIgnoreCase("option"))
{
option = c.getValue();
}
}
}

[REF]http://www.blogjava.net/action/archive/2007/04/10/109574.html

2008年10月19日 星期日

[Java] 串流圖片下載範例

串流圖片下載範例:

Solution1:

URL url = new URL("http://xxx/xxx/image.jpg");
FileOutputStream fos = new FileOutputStream("image.jpg", false);
InputStream is = url.openStream();
int r = 0;
while((r = is.read()) != -1)
fos.write(r);
fos .close();


Solution2:

private static void flash(InputStream in, OutputStream out, int chunkSize){
try {

byte[] b = new byte[chunkSize];
int readLen;

while ((readLen = in.read(b, 0, b.length)) != -1) {
out.write(b, 0, readLen);
}

out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


Solution3:


import java.io.FileOutputStream;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;


public class JpgTest {

public JpgTest() {

try {
JpgTset();
} catch (Exception ex) {

}
}

public void JpgTset()
throws Exception {
URL url = null;
url = new URL("http://www.jsinfo.net/advimage/3721/765_70_cartoon1.jpg");
//File _file = new File("/Order005-0001.jpg"); //讀入文件
//Image src = Toolkit.getDefaultToolkit().getImage("http://www.google.com/images/logo_sm.gif");
// Image src = java.awt.Toolkit.getDefaultToolkit().getDefaultToolkit().createImage("http://www.google.com/images/logo_sm.gif");
Image src = javax.imageio.ImageIO.read(url); //構造Image對象
int wideth = src.getWidth(null); //得到源圖寬
int height = src.getHeight(null); //得到源圖長
BufferedImage tag = new BufferedImage(wideth / 2, height / 2,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, wideth / 2, height / 2, null); //繪製縮小後的圖
FileOutputStream out = new FileOutputStream("c:/765_70_cartoon.jpg"); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); //近JPEG編碼
//System.out.print(width+"*"+height);
out.close();
}

public static void main(String[] args) {
JpgTest untitled11 = new JpgTest();
}
}


[REF]http://www.javaworld.com.tw/jute/post/view?bid=5&id=237541&tpg=1&ppg=1&sty=0&age=0#237541
[REF]http://topic.csdn.net/t/20060310/01/4604719.html

2008年10月18日 星期六

[Java] Quadratic Equation Solver


/*
* ==========================================================================
* This Java Program prompts a user for coefficients in a quadratic equation,
* and computes and prints the roots of the equation.
*
* Written By : Nathan Blattau and Mark Austin July, 1997
* ==========================================================================
*/

import java.lang.Math;
import java.util.*;
import java.io.*;

class Quadratic {

public static void main( String args[] ) {

float fA,fB,fC;
float fRoot1, fRoot2;
float fDiscriminant;
String sLine;

// Print welcome message.

System.out.println("Welcome to The Quadratic Equation Solver");
System.out.println("----------------------------------------");

// Prompt user for coefficients in quadratic equation.

System.out.println("Please Enter coefficients for equation");
System.out.println("a.x^2 + b.x + c");

System.out.println("Coefficent a : ");
sLine = keyboardInput();
fA = Float.valueOf(sLine).floatValue();

System.out.println("Coefficent b : ");
sLine = keyboardInput();
fB = Float.valueOf(sLine).floatValue();

System.out.println("Coefficent c : ");
sLine = keyboardInput();
fC = Float.valueOf(sLine).floatValue();

// Print details of quadratic equation to screen.

System.out.println("The equation you have entered is : ");
System.out.println(+fA+".x^2 + "+fB+".x + "+fC);

// Check for degenerate roots (i.e., fA = fB = zero).

if ( fA==0 && fB==0 ) {
System.out.println("Cannot solve " + fC +" = 0.0");
return;
}

if ( fA==0 && fB !=0 ) {
fRoot1 = -fC/fB;
System.out.println("Degenerate root : Root = "+ fRoot1);
return;
}

// Compute discriminant of quadratic equation.

fDiscriminant = fdiscriminant(fA,fB,fC);

// Case for two real roots.

if ( fDiscriminant >= 0.0 ) {

fRoot1 = (float)(-fB/2.0/fA-(float)Math.sqrt(fDiscriminant) /
2.0 / fA );
fRoot2 = (float)(-fB/2.0/fA+(float)Math.sqrt(fDiscriminant) /
2.0 / fA);

System.out.println("Two real roots : Root1 : " + fRoot1);
System.out.println(" Root2 : " + fRoot2);
return;
}

// Two complex roots

fRoot1 = (float) (-fB/2.0/fA);
fRoot2 = (float) (Math.sqrt(-fDiscriminant)/2.0/fA);

System.out.println("Two complex roots");
System.out.println("Root1 : " + fRoot1 + "+" + fRoot2 + "i");
System.out.println("Root2 : " + fRoot1 + "-" + fRoot2 + "i");
}

/*
* =============================================================
* Method fdiscriminant() : compute discriminant of quadratic
*
* Input : fA, fB, and fC -- coefficients in quadratic equation
* Output : float fReturn -- discriminant of quadratic equation
* =============================================================
*/

static float fdiscriminant(float fA, float fB, float fC) {
float fReturn;

fReturn= (float)(fB*fB-4.0*fA*fC);
return fReturn;
}

/*
* ===========================================================
* Method keyboardInput() : Get line of input from keyboard
*
* Input : None.
* Output : String sLine -- character string of keyboard input
* ===========================================================
*/

static String keyboardInput() {
String sLine;

DataInputStream in = new DataInputStream(System.in);
try{
sLine = in.readLine();
return sLine;
}
catch (Exception e){
return "error";
}
}
}


[REF]http://www.isr.umd.edu/~austin/
[REF]http://www.isr.umd.edu/~austin/book.d/code.d/java.d/Quadratic.java

[Java]使用Jxl api處理Excel檔


import java.io.FileOutputStream;
import java.io.OutputStream;
import jxl.*;
import jxl.write.*;


public class Main {

public static void main(String[] args) {

try {
OutputStream os = new FileOutputStream("Test.xls");
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);

WritableSheet sheet = wwb.createSheet("First Sheet", 0);
Label label = new Label(0, 0, "This is a label");
sheet.addCell(label);
wwb.write();
wwb.close();

} catch (Exception e) {
System.out.println(e);
}

}
}

[REF]http://www.ibm.com/developerworks/cn/java/l-javaExcel/
[REF]http://poplaryy.javaeye.com/blog/187482

[Java] Readers Vs Writers

常見的Java串流使用範例:

緊記:有開檔,必要有關檔

讀檔 :

import java.io.*;

public class Read{

public static void main(String args[]){

String temp;

try{
FileReader myReader = new FileReader("input.txt");
BufferedReader br = new BufferedReader(myReader);
while((temp = br.readLine()) != null){
System.out.println(temp);
}
}catch(Exception e){}
}
}


建檔->寫檔:

import java.io.*;

public class WriteFile{
public static void main(String[] args) throws Exception{
int a;
try{
File MyFile = new File("MyText.txt");
FileWriter MyFileWriter = new FileWriter(MyFile);
BufferedWriter MyFileBuffer = new BufferedWriter(MyFileWriter);
MyFileBuffer.write("Hello World 1\r\n");
MyFileBuffer.write("Hello World 2");
MyFileBuffer.close();
}catch(Exception e){}
}
}



只要將 FileWriter MyFileWriter = new FileWriter(MyFile);
改成 FileWriter MyFileWriter = new FileWriter(MyFile,true);
代表在檔案的尾部寫入!!

開檔->寫檔(接著原檔尾部寫入):

import java.io.*;

public class WriteFile{
public static void main(String[] args) throws Exception{
int a;
try{
File MyFile = new File("MyText.txt");
FileWriter MyFileWriter = new FileWriter(MyFile,true);
BufferedWriter MyFileBuffer = new BufferedWriter(MyFileWriter);
MyFileBuffer.write("Hello World 1\r\n");
MyFileBuffer.write("Hello World 2\r\n");
MyFileBuffer.close();
}catch(Exception e){}
}
}
[REF]http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String,%20boolean)
[REF]http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

2008年10月17日 星期五

[Java][FW]Slider Demo

說明:
預先讀取圖檔,有進度表顯示目前已讀取的進度,讀取完畢後依照順序顯示圖片,每秒切換一張圖片,循環顯示這些圖片。


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

public class Slider extends JPanel
 implements Runnable, ActionListener
{
 // 這裡是要修改的檔案張數
 final int readed_img = 30;

 private Image[] image = new Image[readed_img];
 private int nowindx;
 private Image nowimg;
 private int State;

 private javax.swing.Timer gtimer = new javax.swing.Timer(1000 ,this);
 private MediaTracker tracker = new MediaTracker(this);
 private Font FS = new Font("標準楷",Font.BOLD,35);

 Slider () {
  setLayout(null);
  setPreferredSize(new Dimension(800,600));
  setDoubleBuffered(true);

  for (int i=0 ; i < readed_img ; i++) {
   // 這裡是要修改的圖檔檔名
   image[i] = Tool.getImage("img/gurumins ("+i+").jpg");
   tracker.addImage(image[i], i%5);
  }

  State = LODING_STATE;
  new Thread(this).start();
 }

 public void run() {
  System.out.println("Loading image....");
  try {
   for (int i=0 ; i < readed_img ; i++) {
    tracker.waitForID(i%5);
    now_percent ++;
    repaint();
    // 這裡是delay的時間
    Thread.sleep(100);
   }
   System.out.println("Loading finish....");
   State = SLIDING_STATE;
   nowimg = image[0];
   gtimer.start();
   repaint();
  } catch (InterruptedException e) {
   System.err.println("Loading Image Error Occur");
  }
 }

 public void actionPerformed(ActionEvent e) {
  nowindx = (nowindx+1) % readed_img;
  nowimg = image[nowindx];
  repaint();
 }

 public void update (Graphics g) {
  paint(g);
}

 private int now_percent = 0;

 final int LODING_STATE = 1;
 final int SLIDING_STATE = 2;
 public void paintComponent(Graphics g) {
  g.clearRect(0,0,800,600);
  switch (State) {
   case LODING_STATE:
    g.setFont(FS);
    g.setColor(Color.black);
    g.drawString("Lodaing .....", 110, 300);
    for (int i=0 ; i < now_percent ; i++) {
     g.setColor(Color.yellow);
     // 這裡是可能要修改的進度列拓展寬度
     g.fillRoundRect(100+i*20, 400, 20, 50, 4, 4);
    }
   break;
  
   case SLIDING_STATE:
    g.drawImage(nowimg, 0, 0, this);
    g.setFont(FS);
    g.setColor(Color.blue);
    g.drawString("Now Slider = "+nowindx, 30, 300);
   break;
  }
 }

 public static void main(String[] args) {
  JFrame f = new JFrame("Slider Demo");
  Slider pn = new Slider();
  f.setContentPane(pn);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  f.setResizable(false);
  f.pack();
  f.setVisible(true);
 }
}

class Tool {
 static public Image getImage(String name) {
  java.awt.Image img;
  java.net.URL url;
  try {
   url = Tool.class.getResource(name);
   img = Toolkit.getDefaultToolkit().getImage(url);
   return img;
  } catch (Exception e) {
   System.err.println("Cannot find Image file:"+name);
   return null;
  }
 }
}


[REF]http://codingnote.blogspot.com/2007/07/javaslider-demo.html

[Java]ArrayList.toArray的用法


import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

public class Test {
public static void main(String[] args) {
List list = new ArrayList();
for(int i =0 ;i < 100; i ++){
list.add(i);
}
Integer[] intArray = (Integer[]) list.toArray(new Integer[0]);
for(int i = 0 ; i < intArray.length; i++){
System.out.println("intArray[" + i + "] ==> "+ intArray[i]);
}
}
}

[Java]用Arraylist來排序和過濾陣列(Collections)





import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashSet;

import java.util.List;



public class SortListDemo {



public static class StringComparator> implements Comparator {



public int compare(T o1, T o2) {

if (o1 == null && o2 == null) {

return 0;

} else if (o1 == null) {

return -1;

} else if (o2 == null) {

return 1;

} else {

return o1.compareTo(o2);

}

}

}



public static void main(String[] args) {

List list = new ArrayList();

list.add("111-1111");

list.add("131-1111");

list.add("111-1111");

list.add("131-1111");

list.add("121-1221");

list.add("111-1111");

list.add("111-1111");



SortListDemo sortList = new SortListDemo();



Object[] result = sortList.SortStringList(sortList.removeIterance(list)).toArray();



for (int i = 0; i < result.length; i++) {

System.out.println(result[i]);

}

}



private List removeIterance(List list) {

ArrayList result = new ArrayList();

if (list != null && list.size() > 0) {

HashSet set = new HashSet();

set.addAll(list);

result.addAll(set);

}

return result;

}



private List SortStringList(List list) {

Comparator comp = new StringComparator();

Collections.sort(list, comp);

return list;

}

}



2008年10月16日 星期四

[Java]String與基本資料型態之間的轉換

1. 由基本資料型態轉換成 String
String 類別中已經提供了將基本資料型態轉換成 String 的 static 方法
也就是 String.valueOf() 這個參數多載的方法

有下列幾種

String.valueOf(boolean b) : 將 boolean 變數 b 轉換成字串
String.valueOf(char c) : 將 char 變數 c 轉換成字串
String.valueOf(char[] data) : 將 char 陣列 data 轉換成字串
String.valueOf(char[] data, int offset, int count) :

將 char 陣列 data 中 由 data[offset] 開始取 count 個元素 轉換成字串

String.valueOf(double d) : 將 double 變數 d 轉換成字串
String.valueOf(float f) : 將 float 變數 f 轉換成字串
String.valueOf(int i) : 將 int 變數 i 轉換成字串
String.valueOf(long l) : 將 long 變數 l 轉換成字串
String.valueOf(Object obj) : 將 obj 物件轉換成 字串, 等於 obj.toString()

用法如:

int i = 10;
String str = String.valueOf(i);
這時候 str 就會是 "10"

2. 由 String 轉換成 數字的基本資料型態
要將 String 轉換成基本資料型態轉,大多需要使用基本資料型態的包裝類別
比如說 String 轉換成 byte 可以使用 Byte.parseByte(String s)
這一類的方法如果無法將 s 分析 則會丟出 NumberFormatException


byte :
Byte.parseByte(String s) : 將 s 轉換成 byte
Byte.parseByte(String s, int radix) : 以 radix 為基底 將 s 轉換為 byte
比如說 Byte.parseByte("11", 16) 會得到 17

double :
Double.parseDouble(String s) : 將 s 轉換成 double

float :
Double.parseFloat(String s) : 將 s 轉換成 float

int :
Integer.parseInt(String s) : 將 s 轉換成 int

long :
Long.parseLong(String s) : 將 s 轉換成 long


用法如:

try
{
String str = "1234";
int a = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
System.out.println(" parse int error!! " + e);
}


-------------------------------------------------------------

轉錄自java連線版
發信人: TAHO, 看板: java 精華區
標 題: String與基本資料型態(int byte...等)之間的轉換
發信站: 140.126.22.6 竹師風之坊
Origin: Local

[Java]Use HttpClient Login Websites

要讓以下程式run起來,必須先要...
Step1.取得其相關使用到的API --- 點我下載
Step2.下載回來後,要懂得 Set ClassPath
Step3.另外可以參考這三篇,裡頭的內容都寫的超詳細的。
- Link1
- Link2
Step4.如果不幸的,Step3的連結網頁失效了。可以參考我備份的版本。
- My backup Link1
- My backup Link2
- My backup Link3

//Remember Set The Class Path


import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;

public class JClientLoginTest {
public static void main(String[] args) throws HttpException, IOException {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost( "bbs.cpcw.com" , 80, "http" );

PostMethod post = new PostMethod( "/logging.php?action=login" );
NameValuePair name = new NameValuePair( "username" , "dongle2001" );
NameValuePair pass = new NameValuePair( "password" , "1a9i8h1a" );
NameValuePair quest = new NameValuePair( "questionid" , "0" );
NameValuePair answer = new NameValuePair( "answer" , "" );
NameValuePair cookietime = new NameValuePair( "cookietime" , "315360000" );
NameValuePair submit = new NameValuePair( "loginsubmit" , "提   交" );
post.setRequestBody( new NameValuePair[]{name,pass,quest,answer,cookietime,submit});
int status = client.executeMethod(post);
post.releaseConnection();

CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match("bbs.cpcw.com", 80, "/" , false , client.getState().getCookies());
if (cookies.length == 0) {
System.out.println( "None" );
} else {
for ( int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].toString());
}
}

GetMethod get=new GetMethod("/viewthread.php?tid=883329");
client.executeMethod(get);
String response = new String(get.getResponseBodyAsString().getBytes("8859-1"));
System.out.println(response);
get.releaseConnection();

}
}


不錯的範例網站:
http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

[Java]Get The Google's Searching Page


import java.net.*;
import java.io.*;
public class qwer {

/** Creates a new instance of Main */
public qwer() {}
public static void main(String[] args){
try{
Socket s = new Socket("images.google.com.tw", 80);
String head = "GET /images?gbv=2&um=1&complete=1&hl=zh-TW&lr=lang_zh-CN%7Clang_zh-TW&q=flower&aq=f HTTP/1.0\n" +
"Host: images.google.com.tw\n"+
"From: 2.1.1.1 HTTP/1.0\n"+
"Connection:close\n\n";
BufferedReader in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Test.txt")));


out.print(head);
out.flush();
String line="";
while ((line = in.readLine()) != null){
System.out.println(line);
output.println(line);
}
out.close();
output.close();
in.close();
}catch(Exception e){}
}}