传入任意文本文件,将文章按单词分开并统计出现次数,按字典顺序输出,并存入数据库

本文介绍了一种使用Java实现的文本文件单词统计方法,通过读取文件内容,按单词拆分并统计出现频率,最终按字典顺序输出,并将结果存入数据库。涉及的技术包括文件读写、字符串操作、数据库连接及GUI界面设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传入任意文本文件,将文章按单词分开并统计出现次数,按字典顺序输出,并存入数据库

package fileExplorer;

import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.LinkedHashMap;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;



import java.sql.*;
public class FileExplorer extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	public JPanel panel;
	public JButton openFile;
	public JButton ok;
	public JButton cancel;
	public JTextArea textOut;
	public FileDialog fd;
	public String dir,fileName;
	PreparedStatement psql;

	public FileExplorer() {
		
		panel=new JPanel();
		add(panel);
		panel.setLayout(null);
		
		openFile= new JButton("打开文件");
		openFile.setBounds(250, 40, 100,40);
		panel.add(openFile);
		OpenFileEvent e=new OpenFileEvent();
		openFile.addActionListener(e);
		
		ok=new JButton("确定");
		ok.setBounds(400, 110, 100, 40);
		OkEvent e3=new OkEvent();
		ok.addActionListener(e3);
		panel.add(ok);
		
		cancel=new JButton("取消");
		cancel.setBounds(80, 110, 100, 40);
		CancelEvent e2=new CancelEvent();
		cancel.addActionListener(e2);
		panel.add(cancel);
		
		textOut=new JTextArea();
		textOut.setBounds(15,190,550,350);
		textOut.setLineWrap(true);
		panel.add(textOut);
	}
	public class OpenFileEvent implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
				fd=new FileDialog(new FileExplorer(),"打开文件",FileDialog.LOAD );//新建打开文件对话框,模式为打开模式
				fd.setVisible(true);
				
				
				dir=fd.getDirectory();
				fileName=fd.getFile();//得到选择文件的路径和名字
			//	System.out.println(fileName);
		}
		
	}
	public class CancelEvent implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			System.exit(0);
		}
		
	}
	public class OkEvent implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			StringBuilder text=new StringBuilder();
			File file=new File(dir+fileName);    //根据路径和名字加载文件
			FileReader fr=null;
			try {
				fr = new FileReader(file);
			
			BufferedReader br=new BufferedReader(fr);
			String line="";
			while((line=br.readLine())!=null) {     //按行读取文件,并用append连接
				text.append(line);  
			}
//			textOut.setText(text+"");//文本输出到textArea
			String p1,p2,p3,p4;
			String[] p11,p22,p33,p44;
			p1=String.valueOf(text);       //将text转换为String类型
			p11=p1.split("[?]");			//将text文件按文中的?分开为字符串数组 
//			
			p2=String.join("", p11);		//将分开的字符串数组合并成一个字符串
			p22=p2.split("[!]");
//			
			p3=String.join("", p22);
			p33=p3.split("[.]");
//			
			p4=String.join("", p33);
			p44=p4.split(" ");
			sort(p44);                       //调用sort函数,将字符串数组p44按冒泡法排序

			LinkedHashMap<String, Integer> hashmap=new LinkedHashMap<>();
			for(String str:p44) {
				if(!hashmap.containsKey(str))
				hashmap.put(str, 1);
				else hashmap.put(str,hashmap.get(str)+1);
			}
			
			textOut.setText(hashmap.toString());//在界面输出
			

			Conn conn = new Conn();
            Connection connection = null;  
                connection = conn.getCon();
                System.out.println("数据库连接成功");
                for (String key : hashmap.keySet()) {
                    psql = connection.prepareStatement("insert into word values(?,?)");
                    psql.setString(1, key);
                    psql.setInt(2, hashmap.get(key));
                    psql.executeUpdate();
                }
                psql.close();
                connection.close();
                System.out.println("数据库存放成功!");
		
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			}
		
	}
	//定义排序算法
	public void sort(String[] sortword) {
		String tem;
		for(int i=0;i<sortword.length-1;i++) {
			for(int m=0;m<sortword.length-1-i;m++) {
				if(sortword[m].compareToIgnoreCase(sortword[m+1])>0) {
					tem=sortword[m];
					sortword[m]=sortword[m+1];
					sortword[m+1]=tem;
				}
			}			
		}		
	}
	public static void main(String args[]) {
		FileExplorer fe=new FileExplorer();
		fe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		fe.setSize(600,600);
		fe.setVisible(true);
		fe.setTitle("单词统计程序");
	}
}

数据库连接类
conn.class

package fileExplorer;

import java.sql.*;
public class Conn {
	   //声明Connection对象
    java.sql.Connection con;
    //驱动程序名
    String driver = "com.mysql.jdbc.Driver";
    //URL指向要访问的数据库名mydata
    String url = "jdbc:mysql://localhost:3306/game";
    //MySQL配置时的用户名
    String user = "root";
    //MySQL配置时的密码
    String password = "root";


    public  java.sql.Connection getCon() throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        //1.getConnection()方法,连接MySQL数据库!!
        con = DriverManager.getConnection(url,user,password);
        return con;
    }
}



Gui界面:
panel=new JPanel();
add(panel);
panel.setLayout(null);

	openFile= new JButton("打开文件");
	openFile.setBounds(250, 40, 100,40);
	panel.add(openFile);
	OpenFileEvent e=new OpenFileEvent();
	openFile.addActionListener(e);
	
	ok=new JButton("确定");
	ok.setBounds(400, 110, 100, 40);
	OkEvent e3=new OkEvent();
	ok.addActionListener(e3);
	panel.add(ok);
	
	cancel=new JButton("取消");
	cancel.setBounds(80, 110, 100, 40);
	CancelEvent e2=new CancelEvent();
	cancel.addActionListener(e2);
	panel.add(cancel);
	
	textOut=new JTextArea();
	textOut.setBounds(15,190,550,350);
	textOut.setLineWrap(true);
	panel.add(textOut);

**

遇到的问题:

1. panel的格式调不对,后来发现缺少setlayout(null)函数,导致用默认的样板模式进行输出
按钮的监听器

2. 创建类event实现actionListener的借口,并重载函数实现按钮的事件,按钮处调用.addActionListener()来实现为按钮添加监听器
Split,join函数:

3. 通过字符串的split函数,将字符串根据特定的符号分开,通过String类型的静态函数Join(),将字符串合并成String类型

  1. 运用FileDialog产生选择文件的对话框,选择文件,得到文件的路径和命名。

**5. 哈希表:
本函数调用的事链接哈希表,以string类型为下标,计算各个string的出现的个数,链接哈希表和普通哈希表的区别就是,连接哈希表能够顺序遍历,实现先进先出,后进后出,而哈希表则是乱序遍历

  1. 数据库连接:
    加载驱动程序String driver = “com.mysql.jdbc.Driver”;
    加载数据库String url = “jdbc:mysql://localhost:3306/game”
    连接数据库 Class.forName(driver);
    执行查询 con= DriverManager.getConnection(url,user,password);**

运行截图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值