Java Application

 
 株価情報をテキスト形式のファイルに保存
 電子メール送信
 電子メール受信

 BACK>>


株価情報をテキスト形式のファイルに保存
import java.io.*;
import java.util.*;
import java.net.*;
public class Class1
{
	
	public static void main (String[] args)
	{
		File f1=new File("csv.txt");
		
		//各業種のリンク先を抽出する
		//GetLink gl=new GetLink();
		//gl.getURL();
		
		//GetData gd=new GetData();
		//gd.WriteData();
		
		FromHtmlToCsv ft=new FromHtmlToCsv("file.txt","csv.txt");
		ft.ToCsv();
		
		System.out.println("");
		System.out.println("");
		System.out.println("Finsh!");
		
		try
		{
			System.in.read();
		}
		catch(Exception e){}
			
	}
}
//各業種のリンク先を抽出しhtml.txtとして出力する。
class GetLink
{
	public void getURL()
	{
		String line;
		try
		{
			URL url=new URL("http://www.radio-tampa.com/kabu/g_select_1.html");
			DataInputStream in=new DataInputStream(url.openStream());
			FileOutputStream f1=new FileOutputStream("html.txt");
			DataOutputStream out=new DataOutputStream(f1);
			while ((line=in.readLine())!=null)
			{
				
				String firstpart="<A HREF=";
				int startindex=line.indexOf(firstpart);
				if(startindex !=-1)//<A HREF=が存在する行の場合以下の処理を行う
				{
					String lastpart="html";
					int lastindex=line.indexOf(lastpart);
					String str=line.substring(startindex+9,lastindex+4);//リンク先を切り出す
					out.writeBytes(str+'\n');
					System.out.println(str);
				}
			}
			in.close();
			out.close();
		}
		catch(Exception e){}	
	}
}
class GetData
{
		String line;
        String tampa="http://www.radio-tampa.com/kabu/";
	public void WriteData()
	{
        try
        {
			FileInputStream fs=new FileInputStream("html.txt");
			DataInputStream dis=new DataInputStream(fs);
			
			FileOutputStream file=new FileOutputStream("file.txt");
			DataOutputStream out=new DataOutputStream(file);
			
			
			String check;
			
			while((check=dis.readLine())!=null)//html.txtからリンク先を読み込む。
			{
				
				URL url=new URL(tampa+check);
				System.out.println(tampa+check);				
				DataInputStream in=new DataInputStream(url.openStream());
				while ((line=in.readLine())!=null)
				{
					out.writeBytes(line+'\n');
					
				}
			}
			fs.close();
			file.close();
			out.close();
		}
		catch(Exception e){}
	}
}
//htmlファイルをcsv形式のテキストファイルに変換。
class FromHtmlToCsv
{
	String HtmlFile;
	String CsvFile;
	
	FromHtmlToCsv(String HtmlFile,String CsvFile)//コンストラクターでファイル名を設定する。
	{
		this.HtmlFile=HtmlFile;//入力テキスト
		this.CsvFile=CsvFile;//出力テキスト
	}
	
	void setFile(String HtmlFile,String CsvFile)//これでもファイル名を設定できる。
	{
		this.HtmlFile=HtmlFile;//入力テキスト
		this.CsvFile=CsvFile;//出力テキスト
	}
	public void ToCsv()
	{
		try
		{
			
			FileInputStream fins=new FileInputStream(HtmlFile);//入力テキスト
			DataInputStream in=new DataInputStream(fins);
			
			FileOutputStream fout=new FileOutputStream(CsvFile);//出力テキスト
			DataOutputStream out=new DataOutputStream(fout);
			
			String sep=System.getProperty("line.separator");
			String line;
			String str;
			
			
			while((line=in.readLine()) !=null)//1行取り出す
			{
				int len=line.length();
				if(len >= 4)//行に文字が存在すれば
				{
					str=line.substring(0,4);//2バイト切り取り
					if ("<TD ".equalsIgnoreCase(str))//それが<TDであれば
					{						
						String ini="<";
						String fin=">";
							while(line.indexOf(ini)>=0)//切り取ったlineに "<" が存在するまで繰り返す。
							{								
								int i=line.indexOf(fin);//line の先頭から 最初の">"の位置を調べる。
								int f=line.lastIndexOf(ini);//lineの末尾から "<"の位置を調べる。
								if(f==0)//iとfが逆になるとsubstringできなきなるため。つまりデータがないときの処理
								{
									line="";
									break ;
								}
								line=line.substring(i+1,f);//これで挟まれているタグを切り捨てる。
							}
							
							String pat=","; 
							if(line.indexOf(pat)>0)//データにコンマが存在すれば
							{
								int from =0;
								int index;
								int linelength=line.length();
		
								while((index=line.indexOf(pat,from))>=0)//コンマを削除する。そうしないとコンマ形式のテキストに変換した場合不都合が生じる。
								{									
									line=line.substring(0,index)+line.substring(index+1,linelength);
									from=index+pat.length();
									linelength=line.length();
								}
							}
								
							out.writeBytes(line+",");
					}
					if ("</TR".equalsIgnoreCase(str))//それが</TR>であれば
					{
						out.writeBytes(""+sep);//改行を実行。
					}
				}
				//System.out.println(line);
			}
			
			
			//System.out.println("Finsh");
			
			in.close();
			out.close();
		}
		catch(Exception e){}
	}
}

 BACK>>


 電子メール送信
import java.net.*;
import java.io.*;
import java.util.*;
class Class1
{
	public static void main(String[] args)
	{
		String smtpServ = "smtp.yahoo.com"; // 送信用サーバ
		String yaddr="wataky@yahoo.com";//相手のメールアドレス
		String maddr = "wataky@yahoo.com" ; // 自分のメールアドレス
		String subject="Listen";
		String message="Hi! Hello.日本語はいけるかな";
	    	Mail m = new Mail(smtpServ,yaddr,maddr,subject,message) ;
		m.send();	        
	}
}
// Mailクラス
class Mail
{
    	final int SMTP_PORT = 25;// SMTP接続用ポート番号(25番)
    	String smtp_server = ""; // 送信用サーバ
	String you_email_addr="";//相手のメールアドレス
    	String my_email_addr = "" ; // 自分のメールアドレス
	String subject="";
	String message="";
	Socket smtp;
	BufferedReader smtp_in;
	PrintWriter smtp_out;
	String status="";
	String response;
//////////////////////////////////////////////////
	public String getStatus()
	{
		return status;
	}
/////////////////////////////////////////////////////////////////////////////////
	Mail(String smtpServ,String yaddr,String maddr,String subject,String message)
	{
		this.smtp_server =smtpServ; // 送信用サーバ
		this.you_email_addr=yaddr;//相手のメールアドレス
		this.my_email_addr =maddr; // 自分のメールアドレス
		this.subject=subject;
		this.message=message;
		try
		{
			smtp = new Socket(smtp_server, SMTP_PORT);// CONNECT
			smtp_in =new BufferedReader(new InputStreamReader(smtp.getInputStream()));
			smtp_out = new PrintWriter(smtp.getOutputStream());
			response= smtp_in.readLine();//返答コードの読み取り
			//System.out.println("recv> " + response);
			status="recv> " + response;
		}
		catch(Exception e)
		{
			//System.out.println(e);
			status=""+e;
		}
		
	}
///////////////////sendcommandメソッド//SMTPコマンドをサーバに送信し,返答コードの確認を行います
    public void send_command(Socket smtp, BufferedReader smtp_in, PrintWriter smtp_out, String command,int success_code)
    {
		try
		{
			smtp_out.print(command +"\n");//コマンドの送信
			smtp_out.flush();
			//System.out.println("send> " + command);//送信内容の表示
			status="send> " + command;
			response= smtp_in.readLine();//返答コードの読み取り
			//System.out.println("recv> " + response);
			status="recv> " + response;
			if (Integer.parseInt(response.substring(0,3)) != success_code)//  もし返答コードが期待されるコード(success_code)でなければ・・・
			{
			    smtp.close();// コネクションを閉じます
			}
		}
		catch(Exception e)
		{
			//System.out.println(e);
			status=""+e;
		}
    }
///////////////////// sendメソッド// SMTPのセッションを進めます
    public void send()
    {
		
        // HELOコマンドの送付
        send_command(smtp, smtp_in, smtp_out,"HELO " + smtp_server, 250);
        // MAIL FROMコマンドの送付
        send_command(smtp, smtp_in, smtp_out,"MAIL FROM:" + my_email_addr, 250);
        // RCPT TOコマンドの送付
        send_command(smtp, smtp_in, smtp_out,"RCPT TO:" + you_email_addr, 250);
        // DATAコマンドによるメールの送付
        send_command(smtp, smtp_in, smtp_out, "DATA", 354);
          //Subjectヘッダの送付
		try
		{
			smtp_out.print("Subject:" + subject + "\n");
			//System.out.println("send> " + "Subject:" + subject) ;
			status="send> " + "Subject:" + subject;
			smtp_out.print("\n");
			smtp_out.print(message+"\n");
			//System.out.println("send> " + message) ;
			status="send> " + message;
		}
		catch(Exception e)
		{
			//System.out.println(e);
			status=""+e;
		}
        send_command(smtp, smtp_in, smtp_out, "\r\n.", 250);//復帰改行で.を送信
        // QUITコマンドの送付
        send_command(smtp, smtp_in, smtp_out, "QUIT", 221);
        // コネクションのクローズ
		try
		{
			smtp.close();
			//System.in.read();
		}
		catch(Exception e)
		{
			//System.out.println(e);
			status=""+e;
		}
    }
}
///////////////END/////////////////////////////////////////////////////*/


 BACK>>


電子メール受信

import java.net.*;
import java.io.*;
import java.util.*;
public class Class1
{
	
	public static void main (String[] args)
	{
		Pop p = new Pop() ;
        	p.authorization() ;
		p.transaction();
		p.update();
	}
}
////////////////class Pop///////////////////////////////////////////////////
class Pop {
    final int POP_PORT = 110;// POP接続用ポート番号(110番)
	int message_number;
	String response="";
	boolean cont = true ;
	String pop_server ="pop.ceres.dti.ne.jp" ;
	String username = "wata@ceres" ;
	String password = "19501109" ;
    	BufferedReader pop_in = null ;// 読み出し用ストリーム
    	PrintWriter pop_out = null ;// 書き込み用ストリーム
    	Socket pop = null ;// ソケット
/////////////////// authorizationメソッド// TCPコネクションの設定と認証を行います
    public void authorization() 
    {
		try
		{
			pop = new Socket(pop_server, 110);// サーバとの接続
			pop_in =new BufferedReader(new InputStreamReader(pop.getInputStream()));
			pop_out = new PrintWriter( pop.getOutputStream());
			response = pop_in.readLine();//返答の読み取り
			System.out.println(response) ;
			if (!("+OK".equals(response.substring(0,3))))//  もし返答コードが+OKでなければ・・・
			{
			    pop.close();// コネクションを閉じます
			}
			getSingleLine("USER " + username) ;// USERコマンドとPASSコマンドによる認証作業
			getSingleLine("PASS " + password) ;
			int intial_position=response.indexOf("has");			
			int final_postion=response.indexOf("message");			
			String str=response.substring(intial_position+3,final_postion);
			String str1=str.trim();//ここが問題だった。string中にspaceがあるとNumberFormatExceptionになる。
				try//message_numberの値を得る。
				{
					message_number=Integer.parseInt(str1);//parseIntはtryのなかで。
				}
				catch(NumberFormatException e)
				{
					System.out.println(""+e);
				}
		}
		catch (Exception e){
			System.out.println(e);
		}
    }
////////////////////////////////////////////////////////// 
	public void transaction()
    {
		if(message_number>0)
		{
			for(int i=1;i<=message_number;i++)
			{
				getLines("RETR "+i);
			}
			for(int i=1;i<=message_number;i++)
			{
				getLines("DELE "+i);
			}
		}
		
		
	} 	
	
    
///////////////////////////////// getLinesメソッド// 回答が複数行に渡るコマンドの処理を行います    
    public void getLines(String command) 
    {
        boolean cont = true ;
		String buf = null ;
		try
		{
			pop_out.print(command +"\r\n");// コマンドの送付
			pop_out.flush() ;
			String response = pop_in.readLine();//返答の読み取り
			
			if (!("+OK".equals(response.substring(0,3))))//  もし返答コードが+OKでなければ・・・
			{
			        pop.close();// コネクションを閉じます
			}
			while(cont)
			{// 複数行の読み取り 
			        buf = pop_in.readLine();//一行読み取り
					System.out.println(buf) ;
			        // 行頭の単独ピリオドで終了
			        if(".".equals(buf)) cont = false ;
			}
		}
		catch(Exception e){}
	}
///////////getSingleLineメソッド// 返答が一行となるコマンドの処理を行います
    public void getSingleLine(String command)//messages数をint出返す。
    {
		try// コマンドの送付
		{
			pop_out.print(command +"\r\n");
			pop_out.flush() ;
			System.out.println(command) ;
			response = pop_in.readLine();//返答の読み取り
			System.out.println(response) ;
		    if (!("+OK".equals(response.substring(0,3))))//  もし返答コードが+OKでなければ・・・
			{
				pop.close();// コネクションを閉じます
			}
		}
		catch(Exception e)
		{
		}
    }
/////// updateメソッド POP3のセッションを終了します// QUIT
    public void update()        
    {
		try
		{
			getSingleLine("QUIT");
			pop.close();// コネクションを閉じます
		}
		catch(Exception e)
		{
		}
    }
}
//////////////////////////////////////////////////////////////////END

 BACK>>