package vnet.com.weather1;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import vnet.com.update.Getdata;
/**
* 正则方式抓取新浪天气新闻上的新闻
* 地址http://weather.news.sina.com.cn/weather/news/index.html
* @param args
*/
public class Newlist {
private static final Log log = LogFactory.getLog(Newlist.class);
/**
* 测试
* @param args
*/
public static void main(String args[]){
Newlist n=new Newlist();
String[] k=n.getNewList();
for (int i=0;i } String[] m=n.getNewinfo(\"news/2008/1119/35261.html\"); for (int l=0;l } } /** * 由url地址获得新闻内容string[] * 新闻中的图片下载到本地,文中新闻地址改成本地地址 * @param url * @return */ public String[] getNewinfo(String url){ String URL=\"http://weather.news.sina.com.cn/\"+url; //30是指取30段满足给出的正则条件的字符串,如果只找出10个,那数组后面的全为null String[] s = analysis(\" (.*?) for (int i=0;i Matcher matcher = sp.matcher(s[i]); if (matcher.find()){ String imageurl=analysis(\"src=\\\"(.*?)\\\"\" , s[i] , 1)[0]; if(!imageurl.startsWith(\"http://\")){ imageurl=\"http://weather.news.sina.com.cn/\"+imageurl; } System.out.println(\"新闻有图片:\"+imageurl); String content=getContent(imageurl); String[] images=imageurl.split(\"/\"); String imagename=images[images.length-1]; System.out.println(\"图片名:\"+imagename); try { File fwl = new File(imagename); PrintWriter outl = new PrintWriter(fwl); outl.println(content); outl.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(\"s[i]:\"+s[i]); //修改文件图片地址 s[i]=s[i].replace(analysis(\"src=\\\"(.*?)\\\"\" , s[i] , 1)[0], imagename); } } return s; } public String[] getNewList(){ String url=\"http://weather.news.sina.com.cn/weather/news/index.html\"; return getNewList(getContent(url)); } private String[] getNewList(String content ){ //String[] s = analysis(\"align=\\\"center\\\" valign=\\\"top\\\">src=\\\"../images/a(.*?).gif\\\" width=\\\"70\\\" height=\\\"65\\\">\" , content , 50); String[] s = analysis(\" return s; } private String[] analysis(String pattern, String match , int i){ Pattern sp = Pattern.compile(pattern); Matcher matcher = sp.matcher(match); String[] content = new String[i]; for (int i1 = 0; matcher.find(); i1++){ content[i1] = matcher.group(1); } //下面一段是为了剔除为空的串 int l=0; for (int k=0;k l=k; break; } } String[] content2; if (l!=0){ content2=new String[l]; for (int n=0;n } return content2; }else{ return content; } } /** * 由地址获取网页内容 * @param strUrl * @return private String getContent(String strUrl){ try{ //URL url = new URL(strUrl); //BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); URLConnection uc = new URL(strUrl).openConnection(); //通过修改http头的User-Agent来伪装成是通过浏览器提交的请求 uc.setRequestProperty(\"User-Agent\ \"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)\"); System.out.println(\"-----------------------------------------\"); System.out.println(\"Content-Length: \"+uc.getContentLength()); System.out.println(\"Set-Cookie: \"+uc.getHeaderField(\"Set-Cookie\")); System.out.println(\"-----------------------------------------\"); //获取文件头信息 System.out.println(\"Header\"+uc.getHeaderFields().toString()); System.out.println(\"-----------------------------------------\"); BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream(), \"gb2312\")); String s = \"\"; StringBuffer sb=new StringBuffer(); while((s = br.readLine())!=null){ sb.append(s+\"\\r\\n\"); } System.out.println(\"长度+\"+sb.toString().length()); return sb.toString(); }catch(Exception e){ return \"error open url\" + strUrl; } } */ public static String getContent (String strUrl){ URLConnection uc = null; String all_content=null; try { all_content =new String(); URL url = new URL(strUrl); uc = url.openConnection(); uc.setRequestProperty(\"User-Agent\ \"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)\"); System.out.println(\"-----------------------------------------\"); System.out.println(\"Content-Length: \"+uc.getContentLength()); System.out.println(\"Set-Cookie: \"+uc.getHeaderField(\"Set-Cookie\")); System.out.println(\"-----------------------------------------\"); //获取文件头信息 System.out.println(\"Header\"+uc.getHeaderFields().toString()); System.out.println(\"-----------------------------------------\"); if (uc == null) return null; InputStream ins = uc.getInputStream(); ByteArrayOutputStream outputstream = ByteArrayOutputStream(); byte[] str_b = new byte[1024]; int i = -1; while ((i=ins.read(str_b)) > 0) { outputstream.write(str_b,0,i); } new all_content = outputstream.toString(); // System.out.println(all_content); } catch (Exception e) { e.printStackTrace(); log.error(\"获取网页内容出错\"); }finally{ uc = null; } // return new String(all_content.getBytes(\"ISO8859-1\")); System.out.println(all_content.length()); return all_content; } } 现在的问题是:图片下载不全,我用后面两种getContent方法下图片,下来的图片大小都和文件头里获得的Content-Length,也就是图片的实际大小不符,预览不了。 而且反复测试,两种方法每次下来的东西大小是固定的,所以重复下载没有用? 测试toString后length大小比图片实际的小,而生成的图片比图片数据大。下载后存储过程中图片数据增加了! 图片数据流toString过程中数据大小发生了改变,还原不回来。其它新闻内容没有问题。估计是图片的编码格式等的问题。在图片数据流读过来时直接生成图片就可以了。 public int saveImage (String strUrl){ URLConnection uc = null; try { URL url = new URL(strUrl); uc = url.openConnection(); uc.setRequestProperty(\"User-Agent\ \"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)\"); //uc.setReadTimeout(30000); //获取图片长度 //System.out.println(\"Content-Length: \"+uc.getContentLength()); //获取文件头信息 //System.out.println(\"Header\"+uc.getHeaderFields().toString()); if (uc == null) return 0; InputStream ins = uc.getInputStream(); byte[] str_b = new byte[1024]; int byteRead=0; String[] images=strUrl.split(\"/\"); String imagename=images[images.length-1]; File fwl = new File(imagename); FileOutputStream fos= new FileOutputStream(fwl); while ((byteRead=ins.read(str_b)) > 0) { fos.write(str_b,0,byteRead); }; fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); log.error(\"获取网页内容出错\"); }finally{ uc = null; } return 1; } 方法二: 首先把搜索后的页面用流读取出来,再写个正则,去除不要的内容,再把最后的结果存成xml格式文件、或者直接存入数据库,用的时候再调用 本代码只是显示html页的源码内容,如果需要抽取内容请自行改写public static String regex()中的正则式 package rssTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MyRSS { /** * 获取搜索结果的html源码 * */ public static String getHtmlSource(String url) { StringBuffer codeBuffer = null; BufferedReader in=null; try { 请求. 作用 /** * 为了限制客户端不通过网页直接读取网页内容,就限制只能从浏览器提交 * 但是我们可以通过修改http头的User-Agent来伪装,这个代码就是这个 * */ uc.setRequestProperty(\"User-Agent\ \"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)\"); URLConnection uc = new URL(url).openConnection(); // 读取url流内容 in = new BufferedReader(new InputStreamReader(uc .getInputStream(), \"gb2312\")); codeBuffer = new StringBuffer(); String tempCode = \"\"; // 把buffer内的值读取出来,保存到code中 while ((tempCode = in.readLine()) != null) { codeBuffer.append(tempCode).append(\"\\n\"); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return codeBuffer.toString(); } /** * 正则表达式 * */ public static String regex() { String googleRegex = \" return googleRegex; } /** * 测试用 * 在google中检索关键字,并抽取自己想要的内容 * * */ public static List { List String allHtmlSource = MyRSS .getHtmlSource(\"http://www.google.cn/search?complete=1&hl=zh-CN&newwindow=1&client=aff-os- maxthon&hs=SUZ&q=%E8%A7%81%E9%BE%99%E5%8D%B8%E7%94%B2&meta=&aq=f\"); Pattern pattern = Pattern.compile(regex()); Matcher matcher = pattern.matcher(allHtmlSource); while (matcher.find()) { String urlLink = matcher.group(2); String title = matcher.group(4); title = title.replaceAll(\"\ title = title.replaceAll(\" title = title.replaceAll(\"...\ String content = matcher.group(6); content = content.replaceAll(\"\ content = content.replaceAll(\" content = content.replaceAll(\"...\ newsList.add(urlLink); newsList.add(title); newsList.add(content); } return newsList; } /** * main方法 * */ public static void main(String[] args) { System.out .println(MyRSS .getHtmlSource(\"http://main.house.sina.com.cn/news/zckb/index.html\")); } } 方法三: jsp自动抓取新闻 自动抓取新闻 package com.news.spider; import java.io.File; import java.io.FileFilter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.db.DBAccess; public class SpiderNewsServer { public static void main(String[] args) throws Exception{ //设置抓取信息的首页面 String endPointUrl = \"http://cn.china.cn/zixun/\"; //获得当前时间 Calendar calendar=Calendar.getInstance(); SimpleDateFormat sdf=new SimpleDateFormat(\"yyyy-MM-dd\"); String DateNews = sdf.format(calendar.getTime()); /******************** * 抓取二级URl 开始 * url匹配类型:\"http://cn.china.cn/article/\" */ List listNewsType = new ArrayList(); //取入口页面html WebHtml webHtml = new WebHtml(); String htmlDocuemtnt1 = webHtml.getWebHtml(endPointUrl); if(htmlDocuemtnt1 == null || htmlDocuemtnt1.length() == 0){ return; } String strTemp1 = \"http://cn.china.cn/article/\"; String strTemp2 = \"\"; int stopIndex=0; int startIndex=0; int dd=0; while(true){ dd++; startIndex = htmlDocuemtnt1.indexOf(strTemp1, stopIndex); System.out.println(\"==========\"+startIndex); stopIndex= htmlDocuemtnt1.indexOf(strTemp2, startIndex); System.out.println(\"==========---------\"+stopIndex); if(startIndex!=-1 && stopIndex!=-1){ String companyType=htmlDocuemtnt1.substring(startIndex,stopIndex); System.out.println(\"@@@@@--------\"+companyType); System.out.println(\"@@@@@--------\"+companyType.indexOf(\"\\\"\")); companyType=companyType.substring(0,companyType.indexOf(\"\\\"\")); System.out.println(\"#####--------\"+companyType); listNewsType.add(companyType); } if(dd>10){ break; } if(stopIndex==-1 || startIndex==-1){ break; } } System.out.println(\"listCompanyType=====\"+listNewsType.size()); /** * 抓取二级URl 结束 ********************/ /******************** * 抓取页面内容 开始 */ String title=\"\"; String hometext=\"\"; String bodytext=\"\"; String keywords=\"\"; String counter = \"221\"; String cdate= \"\"; int begainIndex=0;//检索字符串的起点索引 int endIndex=0;//检索字符串的终点索引 String begainStr;//检索开始字符串 String endStr;//检索结束字符串 for (int rows = 1; rows < listNewsType.size(); rows++) { String strNewsDetail = listNewsType.get(rows).toString(); System.out.println(\"strNewsDetail=====\"+strNewsDetail); if(strNewsDetail != null && strNewsDetail.length() > 0){ WebHtml newsListHtml = new WebHtml(); String htmlDocuemtntCom = newsListHtml.getWebHtml(strNewsDetail); System.out.println(\"$$$$$------\"+htmlDocuemtntCom); if(htmlDocuemtntCom == null || htmlDocuemtntCom.length() == 0){ return; } //截取时间 int dateBegainIndex = htmlDocuemtntCom.indexOf(\" System.out.println(\"%%%%%--\"+dateBegainIndex); String newTime htmlDocuemtntCom.substring(dateBegainIndex,dateBegainIndex+20); System.out.println(\"^^^^^^^^^^^^^^^---\"+newTime); String newTimeM newTime.substring(newTime.lastIndexOf(\"-\")+1,newTime.lastIndexOf(\"-\")+3); String dateM = DateNews.substring(DateNews.lastIndexOf(\"-\")+1); System.out.println(\"^^^^^^^^^^^^^^^---\"+newTimeM); System.out.println(\"^^^^^^^^^^^^^^^---\"+dateM); if(newTimeM == dateM || newTimeM.equals(dateM)){ //检索新闻标题 = = begainStr=\" endStr=\" begainIndex=htmlDocuemtntCom.indexOf(begainStr,0); System.out.println(\"&&&&&&------\"+begainIndex); endIndex=htmlDocuemtntCom.indexOf(endStr,0); System.out.println(\"&&&&&&------\"+endIndex); if(begainIndex!=-1 && endIndex!=-1){ title = htmlDocuemtntCom.substring(begainIndex,endIndex).trim(); title = title.substring(title.indexOf(\" title = title.replace(\"'\ title = title.replace(\";\ title = title.replace(\" \ } //检索新闻内容 begainStr=\" endStr=\"\"; begainIndex=htmlDocuemtntCom.indexOf(begainStr,0); endIndex=htmlDocuemtntCom.indexOf(endStr,0); if(begainIndex!=-1 && endIndex!=-1){ bodytext = htmlDocuemtntCom.substring(begainIndex,endIndex).trim(); if(bodytext.indexOf(\" \")>0 bodytext.indexOf(\" \") bodytext.indexOf(\" && && bodytext bodytext.substring(bodytext.indexOf(\" \")+3,bodytext.indexOf(\" = bodytext=bodytext.replace(\" \ bodytext=bodytext.replace(\" bodytext=bodytext.replace(\"\\n\ bodytext=bodytext.replace(\"'\ bodytext=bodytext.replace(\";\ } //简介 if(bodytext.length()>40) hometext = bodytext.substring(0,40)+\"......\"; else{ hometext = bodytext+\"......\"; } //浏览量 String str = String.valueOf(Math.random()); counter = str.substring(str.lastIndexOf(\".\")+1,5); Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cdate = cal.getTimeInMillis()+\"\"; cdate = cdate.substring(0,10); }else{ continue; } } System.out.println(\"-------------------------\"+title); System.out.println(\"-------------------------\"+cdate); System.out.println(\"-------------------------\"+cdate); System.out.println(\"-------------------------\"+hometext); System.out.println(\"-------------------------\"+bodytext); System.out.println(\"-------------------------\"+keywords); System.out.println(\"-------------------------\"+counter); /*String str = \"INSERT INTO ecim_stories(uid,title,created,published,hostname,hometext,bodytext,keywords,counter,topicid,ihome,notifypub,story_type,topicdisplay,topicalign,comments,rating,votes,description) \"; str += \"VALUE (1,'\"+title+\"',\"+cdate+\','\"+keywords+\"',\"+counter+\ DBAccess db = new DBAccess();; if(db.executeUpdate(str)>0) { System.out.println(\"-------------------------成功!!!!!!!!!!\"); }else { System.out.println(\"-------------------------失败!!!!!!!!!!\"); }*/ } /** * 抓取页面内容 结束 ********************/ } } package com.news.spider; import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; public class WebHtml { /** * 根据url,抓取webhmtl内容 * @param url */ public String getWebHtml(String url){ try { URL myURL = new URL(url); URLConnection conn = myURL.openConnection(); BufferedReader reader = new InputStreamReader(conn.getInputStream())); String line = null; StringBuffer document = new StringBuffer(\"\"); while ((line = reader.readLine()) != null){ document.append(line + \"\\n\"); BufferedReader(new } reader.close(); String resutlDocument = new String(document); return resutlDocument; } catch (Exception e) {} return \"\"; } } Java 简易播放器 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.media.*; import java.io.*; import java.util.*;//为了导入Vector //import com.sun.java.swing.plaf.windows.*; public class MediaPlayer extends JFrame implements ActionListener,Runnable { private JMenuBar bar;//菜单条 private JMenu fileMenu,choiceMenu,aboutMenu; private JMenuItem openItem,openDirItem,closeItem,about,infor; private JCheckBoxMenuItem onTop; private boolean top=false,loop;//设定窗口是否在最前面 private Player player;//Play是个实现Controller的接口 private File file,listFile;//利用File类结合JFileChooser进行文件打开操作,后则与list.ini有关 private Container c; //private UIManager.LookAndFeelInfo[] look; private String title,listIniAddress;//标题 private FileDialog fd; private JPanel panel,panelSouth; private Icon icon; //开始进入的时候要显示的图标,它为抽象类,不能自己创建 private JLabel label,listB;//用来显示图标 private JList list;//播放清单 private JScrollPane scroll;//使播放清单具有滚动功能 private ListValues listWriteFile;//用于向文件中读取对象 private ObjectInputStream input;//对象输入流 private ObjectOutputStream output;//对象输出流 private JPopupMenu popupMenu;//鼠标右键弹出菜单 private JMenuItem del,delAll,reName; //弹出菜单显示的菜单项,包 括删除,全部删除和重命名 private Vector fileName,dirName,numList; private String files,dir; private int index;//曲目指针 private Properties prop;//获得系统属性 private int indexForDel;//标志要删除的列表项目的索引 private ButtonGroup buttonGroup;//控制按钮组 private JRadioButtonMenuItem[] buttonValues; private String[] content={\"随机播放\顺序播放\单曲循环\ private DialogDemo dialog1; //private JDialogTest dialog2;//用于显示播放清单 MediaPlayer()//构造函数 { super(\"java音频播放器1.1版\");//窗口标题 c=getContentPane(); c.setLayout(new BorderLayout()); //c.setBackground(new Color(40,40,95)); fileName=new Vector(1); dirName=new Vector(1); numList=new Vector(1);//构造三个容器用于支持播放清单 //vectorToString=new String[]; //prop=new Properties(System.getProperties()); //listIniAddress=prop.getProperty(\"user.dir\")+\"\\\\list.ini\"; //listFile=new File(listIniAddress);//本来这些代码用来取的系统属性,后来 //发现根本就不用这么麻烦 listFile=new File(\"list.ini\");//直接存于此目录 Thread readToList=new Thread(this);//注意编线程程序的时候要注意运行的时候含有的变量亿定义或者初始化, //这就要求线程要等上述所说的情况下再运行,否则很容易发生错误或则异常 list=new JList(); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setSelectionForeground(new Color(0,150,150)); list.setVisibleRowCount(10); list.setFixedCellHeight(12); list.setFixedCellWidth(250); list.setFont(new Font(\"Serif\ list.setBackground(new Color(40,40,95)); list.setForeground(new Color(0,128,255)); //list.setOpaque(false); list.setToolTipText(\"点右键显示更多功能\");//创建播放清单并设置各个属性 list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) //判断是否双击 { index = list.locationToIndex(e.getPoint());//将鼠标坐标转化成list中的选项指针 createPlayer2(); //System.out.println(\"Double clicked on Item \" + index);,此是测试的时候加的 } } /* public void mousePressed(MouseEvent e) { checkMenu(e);//自定义函数,判断是否是右键,来决定是否显示菜单 }*/ public void mouseReleased(MouseEvent e) { checkMenu(e);//与上面的一样,判断是否鼠标右键 } } ); //listB=new JLabel(new ImageIcon(\"qingdan.gif\"),SwingConstants.CENTER); scroll=new JScrollPane(list);//用于存放播放列表 //dialog2=new JDialogTest(MediaPlayer.this,\"播放清单\ //dialog2.setVisible(true); readToList.start();//启动先程,加载播放列表 try { Thread.sleep(10); } catch(InterruptedException e) { e.printStackTrace(); } /*look=UIManager.getInstalledLookAndFeels(); try { UIManager.setLookAndFeel(look[2].getClassName()); SwingUtilities.updateComponentTreeUI(this); } catch(Exception e) { e.printStackTrace(); }*///与下面的代码实现相同的功能,但执行速度要慢,原因:明显转了个大弯 /*try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { e.printStackTrace(); } *///此段代码使执行速度大大降低 bar=new JMenuBar(); setJMenuBar(bar);//此两行创建菜单栏并放到此窗口程序 //bar.setBackground(new Color(48,91,183)); fileMenu=new JMenu(\"文件\"); bar.add(fileMenu); choiceMenu=new JMenu(\"控制\"); bar.add(choiceMenu); aboutMenu=new JMenu(\"帮助\"); bar.add(aboutMenu); openItem =new JMenuItem(\"打开文件\"); openDirItem =new JMenuItem(\"打开目录\"); closeItem =new JMenuItem(\"退出程序\"); openItem.addActionListener(this); openDirItem.addActionListener(this); closeItem.addActionListener(this); fileMenu.add(openItem); fileMenu.add(openDirItem); fileMenu.add(closeItem); onTop=new JCheckBoxMenuItem(\"播放时位于最前面\ choiceMenu.add(onTop); onTop.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(onTop.isSelected()) top=true; else top=false; setAlwaysOnTop(top); } } ); choiceMenu.addSeparator();//加分割符号 buttonGroup=new ButtonGroup(); buttonValues=new JRadioButtonMenuItem[3]; for(int bt=0;bt<3;bt++) { buttonValues[bt]=new JRadioButtonMenuItem(content[bt]); buttonGroup.add(buttonValues[bt]); choiceMenu.add(buttonValues[bt]); } buttonValues[0].setSelected(true); choiceMenu.addSeparator(); /*loopItem=new JCheckBoxMenuItem(\"是否循环\"); choiceMenu.add(loopItem); loopItem.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { loop=!loop; } } );*/ infor=new JMenuItem(\"软件简介\"); aboutMenu.add(infor); infor.addActionListener(this); about=new JMenuItem(\"关于作者\"); about.addActionListener(this); aboutMenu.add(about); //菜单栏设置完毕 panel=new JPanel(); panel.setLayout(new BorderLayout()); c.add(panel,BorderLayout.CENTER); panelSouth=new JPanel(); panelSouth.setLayout(new BorderLayout()); c.add(panelSouth,BorderLayout.SOUTH); icon=new ImageIcon(\"icon\\\\Player.jpg\"); label=new JLabel(icon); panel.add(label); popupMenu=new JPopupMenu(); del =new JMenuItem(\"删除\");//鼠标右键弹出菜单对象实例化 popupMenu.add(del); del.addActionListener(this); delAll =new JMenuItem(\"全部删除\"); popupMenu.add(delAll); delAll.addActionListener(this); reName =new JMenuItem(\"重命名\"); popupMenu.add(reName); reName.addActionListener(this); scroll=new JScrollPane(list);//用于存放播放列表 listB=new ImageIcon(\"icon\\\\qingdan.gif\"),SwingConstants.CENTER); JLabel(new panelSouth.add(listB,BorderLayout.NORTH); panelSouth.add(scroll,BorderLayout.CENTER); dialog1=new DialogDemo(MediaPlayer.this,\"软件说明\"); this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//设定窗口关闭方式 //this.setTitle(\"d\");编译通过,说明可以再次设定标题 this.setLocation(400,250);//设定窗口出现的位置 //this.setSize(350,320);//窗口大小 setSize(350,330); this.setResizable(false);//设置播放器不能随便调大小 this.setVisible(true);//此句不可少,否则窗口会不显示 } public void actionPerformed(ActionEvent e) { if(e.getSource()==openItem)//getSource()判断发生时间的组键 { //System.out.println(\"d\");测试用 openFile(); //createPlayer(); //setTitle(title); } if(e.getSource()==openDirItem)//打开目录 { openDir(); } if(e.getSource()==closeItem)//推出播放器 { exity_n(); //System.exit(0); } if(e.getSource()==about) { JOptionPane.showMessageDialog(this,\"此简易播放器由计科0302\\n\" +\"harly\\n \"+\" 完成 \ \"参与者\ JOptionPane.INFORMATION_MESSAGE); } if(e.getSource()==del) { //index //delPaintList(index); fileName.removeElementAt(indexForDel); dirName.removeElementAt(indexForDel); numList.removeAllElements();//从三个容器里面移除此项 Enumeration enumFile=fileName.elements(); while(enumFile.hasMoreElements()) { numList.addElement((numList.size()+1)+\".\"+enumFile.nextElement()); //numList添加元素,显示播放里表中 } //list.setListData(fileName); list.setListData(numList); if(index else { if(index==indexForDel); else if(index!=0) list.setSelectedValue(numList.elementAt(index-1),true); } //list.setSelectedIndex(index); } if(e.getSource()==delAll)//全部删除 { fileName.removeAllElements(); dirName.removeAllElements(); numList.removeAllElements(); list.setListData(numList); } if(e.getSource()==reName)//重命名 { String name;//=JOptionPane.showInputDialog(this,\"请输入新的名字\"); try { name=reNames(); fileName.setElementAt(name,indexForDel); numList.setElementAt((indexForDel+1)+\".\"+name,indexForDel); } catch(ReName e2)//自定义的异常 { } } if(e.getSource()==infor) { dialog1.setVisible(true); } } public static void main(String[] args) { final MediaPlayer mp=new MediaPlayer(); mp.setIconImage(new ImageIcon(\"icon\\\\mPlayer.jpg\").getImage());//改变默认图标 mp.addWindowListener(new WindowAdapter()//注册窗口事件 { public void windowClosing(WindowEvent e) { //System.exit(0); mp.exity_n(); } } ); System.out.println(\"注意:更新文件列表后,请先正常关闭播放器\" +\"\\n然后再关闭此DOS窗口,否则导致播放列表不能保存!!\"); } private void openFile()//为了界面原因,此代码重写,估计兼容性不好了 { /*JFileChooser fileChooser=new JFileChooser();//文件选择器 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//可以选择文件不能目录 int result=fileChooser.showOpenDialog(this);//创建文件打开对话框,并设定此程序为父窗口监控*/ /*通过result的值来判断文件是否打开成功 *JFileChooser类有很多静态成员变量 **/ /*if(result==JFileChooser.CANCEL_OPTION) { file=null;//file已经在类中定义,如果选择取消,file指向为空 } else { file=fileChooser.getSelectedFile();//获得文件对象 title=file.getAbsolutePath();//取得文件的绝对路径并且赋给title设定标题 }*/ //if(fd==null) //{ //String filename=\"java音频播放器\"; fd = new FileDialog(MediaPlayer.this); //Filters fl=new Filters(); //fd.setFilenameFilter(fl); fd.setVisible(true); if (fd.getFile() != null) { title = fd.getDirectory() + fd.getFile();//原因请见同目录下的FileDialogDemo.java文件 files=fd.getFile(); //dir =fd.getDirectory(); file=new File(title); createPlayer(); } //title=filename; //fd=null;//缺少此句如果第一次打开文件的时候取消操作的时候第二次也不能打开文件了 //} } private void openDir() { JFileChooser fileChooser=new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result=fileChooser.showOpenDialog(MediaPlayer.this); if(result==JFileChooser.CANCEL_OPTION) return; file=fileChooser.getSelectedFile(); if(file==null||file.getName().equals(\"\")) JOptionPane.showMessageDialog(this,\"错误的路径\ \"出错了\ String[] sFiles=file.list(); for(int i=0;i fileName.addElement(sFiles[i]); numList.addElement((numList.size()+1)+\".\"+sFiles[i]); dirName.addElement(file.getAbsolutePath()+\"\\\\\"+sFiles[i]); } list.setListData(numList); /*fd=new FileDialog(MediaPlayer.this); fd.setVisible(true); if(fd.getDirectory()!=null) { File fileDir=new File(fd.getDirectory()); String[] ss=fileDir.list(); for(int i=0;i System.out.println(ss[i]); } }*/ } private void createPlayer() { closePreviosPlayer();//关闭先前的媒体播放器 String extendName=\"此播放格式\"; try { 器好象不支持 \"+title.substring(title.lastIndexOf(\".\")+1)+\"player=Manager.createPlayer(file.toURL());//javax.media.Manager直接继承于java.lang.object,且它为final,不能被继承 player.addControllerListener(new ControllerHand()); player.start(); addList(files); index=fileName.size()-1; list.setSelectedValue(numList.elementAt(index),true); //list.setSelectedIndex(index); //list.setSelectionForeground(Color.blue); setTitle(title); //addList(\"files\");//到播放清单 //title=\"file.getAbsoluteFile()\"; } catch(Exception e) { JOptionPane.showMessageDialog(this,extendName,\"了!!\ setTitle(extendName); } } private void closePreviosPlayer() { if(player==null) return; //player.close();//首先停止播放 /* *不能用上面的代码停止,要用下面的两行取代,否则=player.getVisualComponent();发生异常 出错 Component visual **/ player.stop(); player.deallocate(); //停止播放并且重新装载DateSource Component visual =player.getVisualComponent(); Component control=player.getControlPanelComponent(); if(visual!=null) { panel.remove(visual); } if(control!=null) { panel.remove(control); } } private class ControllerHand implements ControllerListener { public void controllerUpdate(ControllerEvent e) { if(e instanceof RealizeCompleteEvent) { Component visual=player.getVisualComponent(); if(visual!=null) { //System.out.println(\"音频播放器不支持视频图象功能\"); //setTitle(\"音频播放器不支持视频图象功能\"); panel.removeAll(); panel.add(visual,BorderLayout.CENTER); } else { panel.add(label,BorderLayout.CENTER); }///此else语句可以防止因为原来播放视频图象后以后没有界面 Component control=player.getControlPanelComponent(); if(control!=null) { panel.add(control,BorderLayout.SOUTH); } //c.validate(); panel.doLayout(); return; } if (e instanceof EndOfMediaEvent) { /*if (loop) { player.setMediaTime (new Time (0)); player.start (); } return;*/ if(buttonValues[0].isSelected()) { if(fileName.size()==0) return; index=(int)(Math.random()*fileName.size()); } if(buttonValues[1].isSelected()) { if(fileName.size()==0) return;//必须有此if语句,否则当用户把播放列表清空的时候发生异常,偶然的机会发现的 //现在感觉测试软件真是太重要了,看来以后程序做好后要反复测试,考虑各种情况 index=(index+1)%fileName.size(); } if(buttonValues[2].isSelected()) { player.setMediaTime (new Time (0)); player.start(); } createPlayer2(); } } } private void exity_n() { /*int exi; exi=JOptionPane.showConfirmDialog(this,\"真的要离开么?JOptionPane.QUESTION_MESSAGE); 退出程序\\ //if(exi==null) if(exi==JOptionPane.YES_OPTION) { saveList(); System.exit(0); } return;*/ saveList(); System.exit(0); } private void addList(String vf) { //fileReadList=new fileReadList(fdd,) //try //{ //int i=0; //fileName.addElement((fileName.size()+1)+\".\"+vf); fileName.addElement(vf); numList.addElement((numList.size()+1)+\".\"+vf); //fileName.addElement(++i+\".\"+vf); dirName.addElement(title); list.setListData(numList); //} /*catch(Exception e) { e.printStackTrace(); //System.out.println(e.getMessage()); }*/ } private void createPlayer2() { try{title=dirName.elementAt(index).toString();} //title=dirName.elementAt(index).toString(); catch(ArrayIndexOutOfBoundsException e) {return;} file=new File(title); closePreviosPlayer();//关闭先前的媒体播放器 String extendName=\"此播放器格式\"; try 好象不支持 \"+title.substring(title.lastIndexOf(\".\")+1)+\"{ player=Manager.createPlayer(file.toURL());//javax.media.Manager直接继承于java.lang.object,且它为final,不能被继承 player.addControllerListener(new ControllerHand()); player.start(); //list.setSelectedIndex(index); list.setSelectedValue(numList.elementAt(index),true); //list.setSelectionForeground(Color.blue); //list.setSelectedIndex(index); //addList(files); setTitle(title); //addList(\"files\");//到播放清单 } catch(Exception e) { //JOptionPane.showMessageDialog(this,extendName,\"了!!\ 出错 //setTitle(extendName); String ex=null; try{ex=fileName.elementAt(index).toString(); } catch(Exception e1){return;} fileName.removeElementAt(index); numList.removeAllElements(); Enumeration enumFile=fileName.elements(); while(enumFile.hasMoreElements()) { numList.addElement((numList.size()+1)+\".\"+enumFile.nextElement()); } dirName.removeElementAt(index); //list.setListData(fileName); list.setListData(numList); System.out.println(\"已经从播放列表中删除 \"+\"\\\"\"+ex+\"\\\"\"+\" 文件,\" +\"因为此播放器不支持\"+ex.substring(ex.lastIndexOf(\".\")+1)+\"格式,\" +\"不过没有从硬盘真正删除\"); if(numList.size()!=0) { index%=numList.size(); createPlayer2(); } } } private void saveList() { Enumeration enumFile=fileName.elements(); Enumeration enumDir =dirName.elements(); try { output=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(listFile))); while(enumFile.hasMoreElements()) { listWriteFile=new ListValues(enumFile.nextElement().toString(),enumDir.nextElement().toString()); output.writeObject(listWriteFile); } output.flush(); output.close(); } catch(Exception e) { e.printStackTrace(); } /*finally { output.flush(); output.close();//郁闷,这两行不能写在这里,实在是一大遗憾啊,不知道有什么别的方法 }*/ } public void run() { try { Thread.sleep(1); } catch(InterruptedException e) { } try { if(!listFile.exists()) { listFile.createNewFile();//防止不存在此文件发生读取错误,这两行代码保证不存在的情况下自动建立 return; } input=new ObjectInputStream(new BufferedInputStream(new FileInputStream(listFile))); while(true) { listWriteFile=(ListValues)input.readObject(); fileName.addElement(listWriteFile.getFileName()); numList.addElement((numList.size()+1)+\".\"+listWriteFile.getFileName()); dirName.addElement(listWriteFile.getDirName()); } } catch(EOFException e) { try { //if(!fileName.isEmpty()) input.close();//确认有元素存在并加载完毕后关闭输入流 } catch(IOException e1) { JOptionPane.showMessageDialog(MediaPlayer.this,\"文件被非正常关闭\ \"非法关闭\ } } catch(ClassNotFoundException e) { JOptionPane.showMessageDialog(MediaPlayer.this,\"不能创建对象\对象创建失败\ } catch(IOException e) { JOptionPane.showMessageDialog(MediaPlayer.this,\"不能读取文件\ \"读取文件失败\ } finally { try { if(input!=null) input.close(); } catch(IOException e) { } if(dirName.isEmpty())//防止Vector越界 { return; } index=(int)(Math.random()*(fileName.size()));//产生随即数,进行随即播放 list.setListData(numList); //list.setListData(fileName); //list.setSelectedValue(fileName.elementAt(index),true); //list.ensureIndexIsVisible(index);//确保选择项可以看见 //list.setSelectionForeground(Color.green); createPlayer2(); } } private void checkMenu(MouseEvent e) { if(e.isPopupTrigger()) { indexForDel=list.locationToIndex(e.getPoint()); int[] selected={index,indexForDel}; //Point p=new Point(e.getX(),e.getY()); list.setSelectedIndices(selected); popupMenu.show(list,e.getX(),e.getY()); } //list.setSelectedIndex(index); } String reNames() throws ReName//文件该名函数 { String name=JOptionPane.showInputDialog(this,\"请输入新的名字\ if(name==null||name.equals(\"\")) throw new ReName(); //必须把name==null放在前面,否则会发生NullPointerExceptin,这个很好理解, //当我们按了取消后,name会成为空,那么name.equals(\"\")就会发生异常 return name; } class ReName extends Exception//自定义异常来处理文件该名的时候发生输入为空的情形 { } /*class Filters implements FilenameFilter { public boolean accept(File dir,String name) { return (name.endsWith(\".exe\")); } }*/ } DialogDemo.java ----------------------------------------------------------------------- //软件简介框 import java.awt.*; import java.awt.event.*; import javax.swing.*; class DialogDemo extends JDialog { JTextArea field; Container c; String sValue= \"\\n本软件基于java media framework构建,同时我们\" +\"\\n正处于基础java学习阶段,所以功能还不是非常完\" +\"\\n善,难登大雅之堂。\" +\"\\n\\n\功能简介:\" +\"\\n本软件的播放清单文件保存在同目录下的\"+\"\\\"\"+\"list.ini\" +\"\\\"\"+\"文件\"+\"\\n下,如果系统不存在此文件则第一次打开的时候软件\" +\"\\n会自动建立。本软件能打开单个音乐文件或整个音乐\" +\"\\n目录,清单支持右键操作,当在列表中读取到不支持的\" +\"\\n文件时,此软件会自动把那个文件从清单清除,并另\" +\"\\n外播放一首歌。不过此软件有个不足之处,就是当你更\" +\"\\n改了清单的时候,要正常退出,即先关闭播放器,然后\" +\"\\n再关闭DOS窗口,因为我是在关闭播放器的时候保存清单\" +\"\\n文件的。不过你运行我编译出来的jar文件就没有此问题\" +\"\\n如果你使用中遇到任何问题,请通知我们,谢谢你的支持\"; DialogDemo(Frame frame,String title) { super(frame,title); field=new JTextArea(); field.setText(sValue); field.setEditable(false); c=getContentPane(); c.setLayout(new BorderLayout()); c.add(field,BorderLayout.CENTER);//默认为BorderLayout布局 setLocation(80,250); setSize(300,350); setResizable(false); //setVisible(true); } } ListValues.java ------------------------------------------------------------------------------ //列表文件要用的对象 import java.io.Serializable; class ListValues implements Serializable { private String fileName; private String dirFileName; ListValues() { setFileName(\"歌曲名字\"); setDirFileName(\"E:\\\\歌曲名字\"); } ListValues(String fileNameC,String dirFileNameC) { setFileName(fileNameC); setDirFileName(dirFileNameC); } void setFileName(String fileNameC) { fileName=fileNameC; } void setDirFileName(String dirFileNameC) { dirFileName=dirFileNameC; } String getFileName() { return fileName; } String getDirName() { return dirFileName; } } Java 获取优酷视频 import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; /** * 获取优酷视频 * @author sunlightcs * 2011-3-29 * */ public class VideoTest { public static void main(String[] args) throws Exception{ String pic = getElementAttrById(\"s_sina\ int local = pic.indexOf(\"pic=\"); pic = pic.substring(local+4); System.out.println(\"视频缩略图:\"+pic); String flashUrl = getElementAttrById(\"link2\ System.out.println(\"视频地址:\"+flashUrl); String time = getElementAttrById(\"download\ String []arrays = time.split(\"\\\\|\"); time = arrays[4]; System.out.println(\"视频时长:\"+time); } /** * 根据HTML的ID键及属于名,获取属于值 * @param id HTML的ID键 * @param attrName 属于名 * @return 返回属性值 */ private static String getElementAttrById(String Exception{ Document doc = getURLContent(); Element et = doc.getElementById(id); String attrValue = et.attr(attrName); String attrName)throws id, return attrValue; } /** * 获取优酷网页的内容 */ private static Document getURLContent() throws MalformedURLException, IOException, UnsupportedEncodingException { Document doc = Jsoup.connect(\"http://v.youku.com/v_show/id_XMjU0MjI2NzY0.html\") .data(\"query\ .userAgent(\"Mozilla\") .cookie(\"auth\ .timeout(3000) .post(); return doc; } Java MP3播放器 主程序MusicPlayer.java package com.media.project1; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.media.ControllerEvent; import javax.media.ControllerListener; import javax.media.EndOfMediaEvent; import javax.media.Manager; import javax.media.MediaLocator; import javax.media.NoPlayerException; import javax.media.Player; import javax.media.PrefetchCompleteEvent; import javax.media.Time; import javax.swing.ButtonGroup; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.filechooser.FileNameExtensionFilter; public class MusicPlayer implements ActionListener, Serializable, ControllerListener { /** * */ private static final long serialVersionUID = -L; private JFrame frame = null; private JPanel controlPanel = null; private JButton btnPlay = null; private JButton btnPre = null; private JButton btnNext = null; private JScrollPane listPane = null; private JList list = null; private DefaultListModel listModel = null; private JMenuBar menubar = null; private JMenu menuFile = null, menuAbout = null, menuMode = null; private JMenuItem itemOpen, itemOpens, itemExit, itemAbout; private JRadioButtonMenuItem itemSingle, itemSequence; private ListItem currentItem = null; private static Player player = null; private boolean isPause = false; private int mode; private int currentIndex; // icon private ImageIcon iconPlay = new ImageIcon(\"images/play1.png\"); private ImageIcon iconPre = new ImageIcon(\"images/pre1.png\"); private ImageIcon iconNext = new ImageIcon(\"images/next1.png\"); private ImageIcon iconPause = new ImageIcon(\"images/pause1.png\"); /** * @param args */ public static void main(String[] args) { new MusicPlayer(); } public MusicPlayer() { init(); } public void init() { frame = new JFrame(); frame.setTitle(\"音乐播放器\"); frame.setSize(400, 300); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menubar = new JMenuBar(); menuFile = new JMenu(\"文件\"); menuAbout = new JMenu(\"关于\"); menuMode = new JMenu(\"播放模式\"); itemOpen = new JMenuItem(\"添加文件\"); itemOpens = new JMenuItem(\"添加文件夹\"); itemExit = new JMenuItem(\"退出\"); itemAbout = new JMenuItem(\"关于\"); itemOpen.addActionListener(this); itemOpens.addActionListener(this); itemExit.addActionListener(this); itemAbout.addActionListener(this); itemSequence = new JRadioButtonMenuItem(\"顺序播放\"); itemSequence.setSelected(true); itemSingle = new JRadioButtonMenuItem(\"单曲循环\"); itemSequence.addActionListener(this); itemSingle.addActionListener(this); ButtonGroup bg = new ButtonGroup(); bg.add(itemSequence); bg.add(itemSingle); menuFile.add(itemOpen); menuFile.add(itemOpens); menuFile.add(itemExit); menuAbout.add(itemAbout); menuMode.add(itemSequence); menuMode.add(itemSingle); menubar.add(menuFile); menubar.add(menuAbout); menubar.add(menuMode); frame.setJMenuBar(menubar); frame.setLayout(new BorderLayout()); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); btnPlay = new JButton(iconPlay); btnPre = new JButton(iconPre); btnNext = new JButton(iconNext); btnPlay.addActionListener(this); btnPre.addActionListener(this); btnNext.addActionListener(this); controlPanel.add(btnPre); controlPanel.add(btnPlay); controlPanel.add(btnNext); listPane = new JScrollPane(); listModel = load(); // System.out.println(listModel.get(0)); list = new JList(listModel); if (list.getSelectedIndex() == -1 && listModel.size() > 0) { currentItem = (ListItem) listModel.get(0); list.setSelectedIndex(0); currentIndex=0; } listPane.getViewport().add(list); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if(player!=null) { player.close(); btnPlay.setIcon(iconPlay); } currentIndex = list.locationToIndex(e.getPoint()); currentItem = (ListItem) listModel.get(currentIndex); list.setSelectedIndex(currentIndex); play(); } } }); frame.setLayout(new BorderLayout()); frame.add(controlPanel, BorderLayout.NORTH); frame.add(listPane, BorderLayout.CENTER); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == itemOpen) {// add files JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( \"音乐文件\ jfc.setFileFilter(filter); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); jfc.setMultiSelectionEnabled(true); if (jfc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { File[] files = jfc.getSelectedFiles(); for (File f : files) { ListItem item = new ListItem(f.getName(), f .getAbsolutePath()); listModel.addElement(item); } } } else if (e.getSource() == itemOpens) {// add files in a directory JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (jfc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { File directory = jfc.getSelectedFile(); File[] files = directory.listFiles(new java.io.FileFilter() { @Override public boolean accept(File f) { if (f.getName().toLowerCase().endsWith(\".mp3\") || f.getName().toLowerCase().endsWith(\".wav\")) return true; return false; } }); for (File file : files) { ListItem item = new ListItem(file.getName(), file .getAbsolutePath()); listModel.addElement(item); } save(listModel); } } else if (e.getSource() == itemExit) { // exit System.exit(0); } else if (e.getSource() == itemAbout) { // about JOptionPane.showMessageDialog(frame, \"作者qq\"); } else if (e.getSource() == btnPlay) { // play or pause play(); } else if (e.getSource() == btnPre) { // pre music pre(); } else if (e.getSource() == btnNext) {// next music next(); } else if (e.getSource() == itemSequence) { mode = 0; } else if (e.getSource() == itemSingle) { mode = 1; } } // play control /** * 播放 */ public void play() { if (btnPlay.getIcon() == iconPlay) { if (isPause) { player.start(); System.out.println(\"暂停结束\"); isPause = false; } else { try { player = Manager.createPlayer(new MediaLocator(\"file:\" + currentItem.getPath())); player.addControllerListener(this); // 提取媒体内容 player.prefetch(); } catch (NoPlayerException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } btnPlay.setIcon(iconPause); } else { player.stop(); isPause = true; System.out.println(\"暂停\"); btnPlay.setIcon(iconPlay); } } public void next() { if (currentIndex == listModel.getSize() - 1) { currentIndex = 0; } else { currentIndex++; } currentItem = (ListItem) listModel.get(currentIndex); list.setSelectedIndex(currentIndex); Point p = list.indexToLocation(currentIndex); JScrollBar jScrollBar = listPane.getVerticalScrollBar();// 获得垂直转动条 jScrollBar.setValue(p.y);// 设置垂直转动条位置 btnPlay.setIcon(iconPlay); if (player != null) player.close(); isPause = false; play(); } public void pre() { if (currentIndex == 0) { currentIndex = listModel.getSize() - 1; } else { currentIndex--; } currentItem = (ListItem) listModel.get(currentIndex); list.setSelectedIndex(currentIndex); Point p = list.indexToLocation(currentIndex); JScrollBar jScrollBar = listPane.getVerticalScrollBar();// 获得垂直转动条 jScrollBar.setValue(p.y);// 设置垂直转动条位置 btnPlay.setIcon(iconPlay); if (player != null) { player.close(); } isPause = false; play(); } // end play control public DefaultListModel load() { File file = new File(\"list.lst\"); DefaultListModel dlm = new DefaultListModel(); if (file.exists()) { try { ObjectInputStream ois = new ObjectInputStream( new FileInputStream(file)); Integer size = (Integer) ois.readObject(); if (size != 0) { for (int i = 0; i < size; i++) { ListItem item = (ListItem) ois.readObject(); dlm.addElement(item); } } ois.close(); return dlm; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return dlm; } public void save(DefaultListModel dlm) { try { ObjectOutputStream oos = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(\"list.lst\"))); Integer size = dlm.getSize(); oos.writeObject(size); for (int i = 0; i < size; i++) { ListItem item = (ListItem) dlm.get(i); oos.writeObject(item); } oos.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void controllerUpdate(ControllerEvent e) { if (e instanceof EndOfMediaEvent) { if (mode == 0) {// 顺序播放 System.out.println(\"顺序播放\"); next(); } else if (mode == 1) { // 单曲循环 System.out.println(\"播放结束\"); player.setMediaTime(new Time(0)); System.out.println(\"单曲循环\"); player.start(); } return; } // 当提取媒体的内容结束 if (e instanceof PrefetchCompleteEvent) { System.out.println(\"开始播放\"); player.start(); return; } } } ListItem类 package com.media.project1; import java.io.Serializable; public class ListItem implements Serializable { /** * */ private static final long serialVersionUID = -L; private String name; private String path; public ListItem() { } public ListItem(String name, String path) { this.name = name; this.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String toString() { return name; } } Java 写的俄罗斯方块 /* 请先安装jdk 游戏操作说明: 编译:javajavajavajavajavajavajavac tetris. 运行:appletviewer tetris. 记得用鼠标在界面上点击一下哈(这样才能响应键盘动作) 左--j 右--l 旋转--i 快速下落--u 直接下落--k 游戏结束后重新开始--s */ import .awt.*; import .applet.*; //为随机数增加的头文件 import .util.*; //为键盘事件增加的头文件 import .awt.event.*; //把所有的 internal 替换成两个空格 //把所有的 rnd.Next 替换成 rnd.nextInt //把所有的 [,] 替换成 [][] //把所有的 bool 替换成 boolean //不会在构造函数中给一维数组赋值:( //namespace Tetris //{ class tetrisdatas { private int[] bricks = {3168,1224,1728,2244,3712,2188,736,3140,2272,1100,3616,3208,1248,1220,228,2248,3840,17476,3264}; private int[] start_bricks = {0,2,4,8,12,16,18}; private Random rnd = new Random(); //int[,] arr=new int[50,50]; int [][]arr=new int [50][50]; int cur_brick=0,next_brick=0,cur_a=0,cur_b=0; int hight=22; private int NewChange=0; private int MayDown=0; int NewHight=0; int level=0; int score=0; int lines=0; int cur_color=0; int next_color=0; public tetrisdatas() { //bricks = new int[19]{3168,1224,1728,2244,3712,2188,736,3140,2272,1100,3616,3208,1248,1220,228,2248,3840,17476,3264}; //start_bricks = new int[7]{0,2,4,8,12,16,18}; cur_brick=start_bricks[(rnd.nextInt()%7+6)%7]; next_brick=start_bricks[(rnd.nextInt()%7+6)%7]; cur_color=(rnd.nextInt()%7+6)%7+1; next_color=(rnd.nextInt()%7+6)%7+1; cur_a=0; cur_b=4; } int get_brick(int index) { return bricks[index]; } boolean may(int a,int b) { boolean flag=true; int num=bricks[cur_brick]; a+=cur_a; b+=cur_b; for(int i=0;i<16;i++) { if( (num>>(15-i)&1)!=0 ) { if( (a+i/4>22)||(b+i%4<0)||(b+i%4>11) ) { flag=false; break; } if( (arr[a+i/4][b+i%4]>0) ) { flag=false; break; } } } return flag; } void move(int a,int b) { cur_a+=a; cur_b+=b; } boolean may_change( ) { boolean rel=true; boolean flag=false; int mid=cur_brick,midd=cur_brick; if(cur_brick==18)//如果是方块,则不能进行如下处理(旋转),否则indexoutofrange return false; for(int i=0;i<7;i++) { if(mid+1==start_bricks[i]) { mid=start_bricks[i-1]; flag=true; break; } } if(!flag) mid++;//方块旋转后,此处会有异常 cur_brick=mid; if(may(0,0)) { NewChange=cur_brick; } else { rel=false; } cur_brick=midd; return rel; } void change( ) { cur_brick = NewChange; } boolean may_down( ) { MayDown=cur_a; for(int i=1;i<23-MayDown;i++) if(!may(i,0)) { MayDown=i-1; break; } return true; } void down( ) { cur_a+=MayDown; } void addto( ) { int num=bricks[cur_brick]; for(int i=0;i<16;i++) { if( (num>>(15-i)&1)!=0 ) { arr[cur_a+i/4][cur_b+i%4]=cur_color; if(cur_a+i/4 } } } void get_next( ) { cur_a=0; cur_b=5; cur_brick=next_brick; next_brick=start_bricks[(rnd.nextInt()%7+6)%7]; cur_color=next_color; next_color=(rnd.nextInt()%7+6)%7+1; } boolean cancel( ) { int line=0; boolean flag; for(int i=cur_a;i flag=true; for(int j=0;j<12;j++) { if(arr[i][j]==0) { flag=false; break; } } if(flag) { line++; for(int k=i-1;k>=hight;k--) for(int j=0;j<12;j++) { arr[k+1][j]=arr[k][j]; arr[k][j]=0; } } } NewHight=hight+line; score+=line*line*10; if(score>(level+1)*200) { level++; if(level>9) level=9; } if(line>0) { lines+=line; return true; } else return false; } int get_speed( ) { return (500-level*45); } void new_hight( ) { hight=NewHight; } boolean gameover( ) { if(!may(0,0)) return true; return false; } void clear() { for(int i=0;i<50;i++) for(int j=0;j<50;j++) arr[i][j]=0; level=0; score=0; lines=0; hight=22; } } //} /* class keyhit extends KeyListener { void KeyPressed(KeyEvent e) {} void KeyReleased(KeyEvent e) {} void KeyTyped(KeyEvent e) {} } */ public class tetris extends Applet implements Runnable { private Image bgImage; private Graphics bg; int x = 100; int y = 20; int r = 10; int game_over=0; char keyhit; private tetrisdatas tt=new tetrisdatas(); public void init() { addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { this_keyPressed(e); } } ); } public void start() { Thread th=new Thread(this); th.start(); } public void stop() {} public void destroy() {} public void run() { while(game_over==0) { repaint(); try { Thread.sleep(tt.get_speed()); } catch (InterruptedException ex) {} if( tt.may(1,0) )//can drop { tt.move(1,0); } else { if(tt.gameover())//game over { game_over=1; } else//new brick { deal_block(); } } } } public void paint(Graphics g) { g.drawRect(9,9,122,232); draw_bricks(g,tt.cur_a,tt.cur_b,tt.cur_brick,tt.cur_color); draw_bricks(g,9,13,tt.next_brick,tt.next_color); draw_base_all(g); draw_small(g,tt.hight,12,3); Color ff = new Color(0,0,0); g.setColor(ff); g.drawString(\"level:\"+tt.level,140,50); g.drawString(\"lines:\"+tt.lines,140,70); g.drawString(\"score:\"+tt.score,140,90); } public void this_keyPressed(KeyEvent e) { keyhit=e.getKeyChar(); if(game_over==0) { if(keyhit=='j' && tt.may(0,-1)) tt.move(0,-1); else if(keyhit=='i' && tt.may_change( )) tt.change( ); else if(keyhit=='l' && tt.may(0,1)) tt.move(0,1); else if(keyhit=='k' && tt.may_down( )) { tt.down( ); deal_block(); } else if(keyhit=='u') { for(int i=3;i>0&&i<23;i--) { if(tt.may(i,0)) { tt.move(i,0); break; } } } repaint(); } if(keyhit=='s' && game_over==1) { tt.clear( ); game_over=0; repaint(); this.start(); } } //添加一些画图函数 public void draw_small(Graphics g,int a,int b,int cl) { int [] red= {255, 0, 255,40, 150,160,70,155}; int [] green={255, 200,0, 2, 38, 97,153,0}; int [] blue= {255,0, 50, 154,44, 90,0 ,100}; Color col = new Color(red[cl],green[cl],blue[cl]); Color white = new Color(255,255,255); g.setColor(col); g.fillRect(b*10+10,a*10+10,10,10); g.setColor(white); g.drawRect(b*10+10,a*10+10,10,10); } public void draw_bricks(Graphics g,int a,int b,int index,int cl) { int bricks_value=tt.get_brick(index); for(int i=0;i<16;i++) { if( (bricks_value>>(15-i)&1)!=0 ) { draw_small(g,a+i/4,b+i%4,cl); } } } public void draw_base_all(Graphics g) { int k=tt.hight; for(int i=k;i<23;i++) for(int j=0;j<12;j++) { if(tt.arr[i][j] != 0) draw_small(g,i,j,tt.arr[i][j]); } } public void deal_block() { tt.addto( ); if(tt.cancel( ))//有可消的行 { tt.new_hight( ); } tt.get_next( ); if(tt.gameover())//game over { game_over=1; } } }// 因篇幅问题不能全部显示,请点此查看更多更全内容
\";\")+4,title.indexOf(\"
\"));
\