Java实现简易的文本编辑器
需求分析:
- 获得文本名称
- 实现尾部追加功能
- 实现覆盖式添加数据
- 删除数据
- 获取光标位置
- 在特定光标位置处添加数据
- 查找特定字符串在主串中第一次出现的位置
统计文本文件内出现的数字,汉字,英文字母,特殊字符的个数,及总的字符个数
开发环境:
windows7 + Eclipse luna + WindowsBuilder插件
代码实现:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Test extends JFrame {
private JPanel contentPane;
private static File file = null;
static int CursorPosition=-1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
file = new File("F://test.txt");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 720, 480);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea taShow = new JTextArea();
taShow.setLineWrap(true);
taShow.setBounds(21, 41, 400, 359);
JLabel label = new JLabel("\u6587\u672C\u9884\u89C8\u533A\uFF1A");
label.setBounds(21, 16, 89, 15);
contentPane.add(label);
JTextArea taEdit = new JTextArea();
taEdit.setLineWrap(true);
taEdit.setBounds(449, 41, 233, 131);
contentPane.add(taEdit);
taShow.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
taShow.setText("您打开的文件的内容是:" + fileContent);
CursorPosition = e.getDot();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
contentPane.add(taShow);
JButton btnGetName = new JButton("\u6587\u6863\u540D\u79F0");
btnGetName.setBounds(449, 211, 93, 23);
btnGetName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
fileTitle = file.getName().toString();
taEdit.setText("您打开的文件的名称是:" + fileTitle);
taShow.setText("您打开的文件的内容是:" + fileContent);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
contentPane.add(btnGetName);
JButton btnAppend = new JButton("\u8FFD\u52A0");
btnAppend.setBounds(449, 261, 93, 23);
btnAppend.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String temp = taEdit.getText().toString();
method1("F://test.txt", temp);
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
fileTitle = file.getName().toString();
taEdit.setText("您打开的文件的名称是:" + fileTitle);
taShow.setText("您打开的文件的内容是:" + fileContent);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
contentPane.add(btnAppend);
JButton btnOverride = new JButton("\u8986\u76D6");
btnOverride.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)));
out.write(taEdit.getText().toString());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException le) {
le.printStackTrace();
}
}
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
fileTitle = file.getName().toString();
taEdit.setText("您打开的文件的名称是:" + fileTitle);
taShow.setText("您打开的文件的内容是:" + fileContent);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnOverride.setBounds(449, 308, 93, 23);
contentPane.add(btnOverride);
JButton btnSearch = new JButton("\u67E5\u627E");
btnSearch.setBounds(449, 357, 93, 23);
btnSearch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
taShow.setText("您打开的文件的内容是:" + fileContent);
String p = taEdit.getText().toString().trim();
taShow.setText(fileContent+"\n\n"+"您查找的字符串第一次出现的位置是:"+fileContent.indexOf(p));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
contentPane.add(btnSearch);
JButton btnPosition = new JButton("\u5149\u6807\u4F4D\u7F6E");
btnPosition.setBounds(589, 211, 93, 23);
btnPosition.enable(false);
contentPane.add(btnPosition);
JButton btnInsert = new JButton("\u5B9A\u70B9\u63D2\u5165");
btnInsert.setBounds(589, 261, 93, 23);
btnInsert.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
String temp=taEdit.getText().toString();
sb.insert(CursorPosition, temp);
method1("F://test.txt", sb.toString());
taShow.setText(sb.toString());
taEdit.setText("定点的数据插入成功执行!");
}catch(Exception ev){
ev.printStackTrace();
}
}
});
contentPane.add(btnInsert);
JButton btnDelete = new JButton("\u5220\u9664");
btnDelete.setBounds(589, 308, 93, 23);
btnDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)));
out.write("");
taShow.setText("删除操作已完成,请到相应路径下查看!");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException le) {
le.printStackTrace();
}
}
}
});
contentPane.add(btnDelete);
JButton btnTotal = new JButton("\u7EDF\u8BA1");
btnTotal.setBounds(589, 357, 93, 23);
btnTotal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
new Total().find(fileContent);
String flag = "数据信息统计结果如下:" + "\n" + "汉字数目:";
flag += new Total().chineseCount;
flag += "\n英文字母个数:";
flag += new Total().englishCount;
flag += "\n特殊字符个数:";
flag += new Total().numberCount;
flag += "\n总的字符个数为:"
+ (new Total().chineseCount
+ new Total().englishCount + new Total().numberCount);
taShow.setText(flag);
new Total().chineseCount = 0;
new Total().englishCount = 0;
new Total().numberCount = 0;
} catch (Exception ec) {
ec.printStackTrace();
}
}
});
contentPane.add(btnTotal);
JLabel label_1 = new JLabel("\u6587\u672C\u7F16\u8F91\u533A\uFF1A");
label_1.setBounds(449, 16, 93, 15);
contentPane.add(label_1);
}
public static void method1(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下面解释一下为什么没有做好注释合作说明文档,因为我做注释做到一半的时候,出现了一点事故,导致没有来得及保存的文件丢失了,所以,请大家谨记,时刻记得保存编辑的被容,否则后果真的很严重。
代码追补解释,下面的代码块是我程序里面做的不好的,违背了代码的复用性原则,请予以为戒:
代码块1:
//代码的作用就是实现对特定的文件进行读取,并存入到String中,方便使用
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
taShow.setText("您打开的文件的内容是:" + fileContent);
CursorPosition = e.getDot();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
代码块2:
//代码实现了向特定的文件内追加数据,若想要覆盖式追加,把参数true去掉即可,默认为覆盖式添加数据
public static void method1(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码块3:
在统计模块中:
btnTotal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
String length = "";
String fileTitle;
String fileContent;
try {
BufferedReader reader = new BufferedReader(new FileReader(
"F://test.txt"));
while ((length = reader.readLine()) != null) {
sb.append(length);
}
fileContent = sb.toString();
new Total().find(fileContent);
String flag = "数据信息统计结果如下:" + "\n" + "汉字数目:";
flag += new Total().chineseCount;
flag += "\n英文字母个数:";
flag += new Total().englishCount;
flag += "\n特殊字符个数:";
flag += new Total().numberCount;
flag += "\n总的字符个数为:"
+ (new Total().chineseCount
+ new Total().englishCount + new Total().numberCount);
taShow.setText(flag);
new Total().chineseCount = 0;
new Total().englishCount = 0;
new Total().numberCount = 0;
} catch (Exception ec) {
ec.printStackTrace();
}
}
其中使用到的new Total().find()方法,详见下面的代码:
package Editer;
/**
* 分别统计出其中字符串中汉字,英文字母,数字,其他字符数量
* @author wWX154783
*
*/
public class Total
{
static String E1,E2,E3;
String str="a12中国3@b&4语*言3c";
static int chineseCount = 0;
static int englishCount = 0;
static int numberCount = 0;
public void find(String str)
{
String E1 = "[\u4e00-\u9fa5]";// 中文
String E2 = "[a-zA-Z]";// 英文
String E3 = "[0-9]";// 数字
String temp;
for (int i = 0; i < str.length(); i++)
{
temp = String.valueOf(str.charAt(i));
if (temp.matches(E1))
{
chineseCount++;
}
if (temp.matches(E2))
{
englishCount++;
}
if (temp.matches(E3))
{
numberCount++;
}
}
System.out.println("汉字数:" + chineseCount);
System.out.println("英文数:" + englishCount);
System.out.println("数字数:" + numberCount);
System.out.println("特殊字符:" + (str.length() - (chineseCount + englishCount + numberCount)));
}
}
好了,下面是程序运行后得到的界面,在此我要声明的是,程序仍然存在一些bug,表现在获得光标位置时的java.lang.IllegalStateException: Attempt to mutate in notification异常,主要还是线程相关,如果博友能解决,还望不吝赐教
能力有限,希望和大家一起进步,一同提高!
接下来的是我从网上找到的一份用C语言实现的简易的文本编辑器的实现,个人认为较之,我的简直就是太菜了,现在将代码贴出来,希望这篇C语言的经典能让更多的人知晓:
#include <stdio.h>
#define MAXLEN 80
#define MAXLINE 200
char buffer[MAXLEN],fname[120];
char *lineptr[MAXLINE];
FILE *fp;
void edit(),replace(),insert(),delete(),quit();
char comch[]="EeRrIiDdQq";/*命令符*/
void(*comfun[])()={edit,replace,insert,delete,quit};/*对应处理函数*/
int modified=0,/*正文被修改标志*/
last;/*当前正文行数*/
char *chpt;/*输入命令行字符指针*/
main()
{
int j;
last=0;
while(1)
{
printf("\nInput a command:[e,r,i,d,q].\n");
gets(buffer);/*读入命令行*/
for(chpt=buffer;*chpt=='\0'||*chpt=='\t';chpt++);/*掠过空白符*/
if(*chpt=='\0') continue;/*空行重新输入*/
for(j=0;comch[j]!='\0'&&comch[j]!=*chpt;j++);/*查命令符*/
if(comch[j]=='\0') continue;/*非法命令符*/
chpt++;/*掠过命令符,指向参数*/
(*comfun[j/2])();/*执行对应函数*/
fprintf(stdout,"The text is:\n");
for(j=0;j<last;j++)/*显示正文*/
fputs(lineptr[j],stdout);
}
}
void quit()
{
int c;
if(modified)/* 如正文被修改 */
{
printf("Save? (y/n)");
while(!(((c=getchar())>='a'&&c<='z')||(c>='A'&&c<='Z')));
if(c=='y'||c=='Y')
save(fname); /* 保存被修改过的正文 */
}
for(c=0;c<last;c++)
free(lineptr[c]); /* 释放内存 */
exit(0);
}
void insert()
{
int k,m,i;
sscanf(chpt,"%d%d",&k,&m); /* 读入参数 */
if(m<0||m>last||last+k>=MAXLINE)/* 检查参数合理性 */
{
printf("Error!\n");
return;
}
for(i=last;i>m;i--)/* 后继行向后移 */
lineptr[i+k-1]=lineptr[i-1];
for(i=0;i<k;i++) /* 读入k行正文,并插入 */
{
fgets(buffer,MAXLEN,stdin);
lineptr[m+i]=(char *)malloc(strlen(buffer)+1);
strcpy(lineptr[m+i],buffer);
}
last+=k; /* 修正正文行数 */
modified=1; /* 正文被修改 */
}
void delete()
{
int i,j,m,n;
sscanf(chpt,"%d%d",&m,&n); /* 读入参数 */
if(m<=0||m>last||n<m) /* 检查参数合理性 */
{
printf("Error!\n");
return;
}
if(n>last)
n=last; /* 修正参数 */
for(i=m;i<=n;i++) /* 删除正文 */
free(lineptr[i-1]);
for(i=m,j=n+1;j<=last;i++,j++)
lineptr[i-1]=lineptr[j-1];
last=i-1; /* 修正正文行数 */
modified=1; /* 正文被修改 */
}
void replace()
{
int k,m,n,i,j;
sscanf(chpt,"%d%d%d",&k,&m,&n); /* 读入参数 */
if(m<=0||m>last||n<m||last-(n-m+1)+k>=MAXLINE)/* 检查参数合理性 */
{
printf("Error!\n");
return;
}
/* 先完成删除 */
if(n>last)
n=last; /* 修正参数 */
for(i=m;i<=n;i++) /* 删除正文 */
free(lineptr[i-1]);
for(i=m,j=n+1;j<=last;i++,j++)
lineptr[i-1]=lineptr[j-1];
last=i-1;
/* 以下完成插入 */
for(i=last;i>=m;i--)
lineptr[i+k-1]=lineptr[i-1];
for(i=0;i<k;i++)
{
fgets(buffer,MAXLEN,stdin);
lineptr[m+i-1]=(char *)malloc(strlen(buffer)+1);
strcpy(lineptr[m+i-1],buffer);
}
last+=k; /* 修正正文行数 */
modified=1; /* 正文被修改 */
}
save(char *fname) /* 保存文件 */
{
int i;
FILE *fp;
if((fp=fopen(fname,"w"))==NULL)
{
fprintf(stderr,"Can't open %s.\n",fname);
exit(1);
}
for(i=0;i<last;i++)
{
fputs(lineptr[i],fp);
free(lineptr[i]);
}
fclose(fp);
}
void edit() /* 编辑命令 */
{
int i;
FILE *fp;
i=sscanf(chpt,"%s",fname); /* 读入文件名 */
if(i!=1)
{
printf("Enter file name.\n");
scanf("%s",fname);
}
if((fp=fopen(fname,"r"))==NULL) /* 读打开 */
{
fp=fopen(fname,"w"); /* 如不存在,则创建文件 */
fclose(fp);
fp=fopen(fname,"r"); /* 重新读打开 */
}
i=0;
while(fgets(buffer,MAXLEN,fp)==buffer)
{
lineptr[i]=(char *)malloc(strlen(buffer)+1);
strcpy(lineptr[i++],buffer);
}
fclose(fp);
last=i;
}
Java实现简易的文本编辑器的更多相关文章
- 简易富文本编辑器bootstrap-wysiwyg源码注释
好久没写随笔了,因为最近比较忙,小公司基本都是一个前端干所有属于和部分不属于前端的事情,所以就没空弄了,即使想分享,也因为没有时间和精力就搁置了. 这周周六日休息,正好时间比较充裕(ps:目前处在单休 ...
- Java开发之富文本编辑器TinyMCE
一.题外话 最近负责了一个cms网站的运维,里面存在很多和编辑器有关的问题,比如编辑一些新闻博客,论文模块.系统采用的是FCKEditor,自我感觉不是很好,如下图 特别是在用户想插入一个图片的话,就 ...
- C++ mfc 简易文本编辑器 遇到的一些问题
[题目40]简易文本编辑器. 设计一个简易的文本编辑器. 设计要求: (1) 具有图形菜单界面: (2) 查找,替换(等长,不等长),插入(插串,文本块的插入).文本块移动(行块,列块移动),删除; ...
- Java-Swing中使用Web富文本编辑器
资料下载 (截取出了邮件发送的功能.) 2018/11/10 因为要 win7 电脑 IE 8 的原因,使用了 jxBrower 拓展,更容易使用,参考链接(推荐) 问题介绍 window客户端软件的 ...
- Java实现"命令式"简易文本编辑器原型
源自早先想法, 打算从界面方向做些尝试. 找到个简单文本编辑器的实现: Simple Text Editor - Java Tutorials. 原本的菜单/按钮界面如下. 包括基本功能: 新建/打开 ...
- java文本编辑器5
package peng_jun; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.* ...
- Java编写的文本编辑器(菜鸟作品)
//这是主窗体文件 Wordwin.java import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.sw ...
- java文本编辑器v2.0 图形用户界面
package 文本编辑器; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; impor ...
- 前后端分离ueditor富文本编辑器的使用-Java版本
最近在写一个自己的后台管理系统(主要是写着玩的,用来熟悉后端java的知识,目前只是会简单的写点接口),想在项目中编写一个发布新闻文章的功能,想到了使用百度的ueditor富文本编辑器,网上找了很多j ...
随机推荐
- PHP Switch 语句
PHP Switch 语句 switch 语句用于根据多个不同条件执行不同动作. PHP Switch 语句 如果您希望有选择地执行若干代码块之一,请使用 switch 语句. 语法 switch ( ...
- PHP 高级过滤器
PHP 高级过滤器 检测一个数字是否在一个范围内 以下实例使用了 filter_var() 函数来检测一个 INT 型的变量是否在 1 到 200 内: 实例 <?php$int = 122; ...
- Detailed Item Cost Report (XML) timed out waiting for the Output Post-processor to finish
In this Document Symptoms Cause Solution References APPLIES TO: Oracle Cost Management - Ver ...
- ubuntu日志文件管理
众所周知,ubuntu的日志文件会越来越大,需要定期管理 logrotate是个十分有用的工具,它可以自动对日志进行截断(或轮循).压缩以及删除旧的日志文件.例如,你可以设置logrotate,让/v ...
- Android Multimedia框架总结(十六)Camera2框架之openCamera及session过程
转载请把头部出处链接和尾部二维码一起转载,本文出自逆流的鱼yuiop:http://blog.csdn.net/hejjunlin/article/details/52942533 前言:前一篇介绍了 ...
- 网络爬虫框架Scrapy简介
作者: 黄进(QQ:7149101) 一. 网络爬虫 网络爬虫(又被称为网页蜘蛛,网络机器人),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本:它是一个自动提取网页的程序,它为搜索引擎从万维 ...
- 传Lua对象到Cpp
传Lua对象到Cpp (金庆的专栏) 摘自:http://raycast.net/lua-intf 以下代码演示了Lua函数和表传入Cpp进行处理: std::string acceptStuff(L ...
- NuGet包断线续传下载
NuGet包断线续传下载(金庆的专栏)NuGet是VC的扩展,用来下载依赖包.NuGet下载没有断线续传,下载源又很容易断开. https://nuget.org/api/v2/ https:// ...
- 没事不要在for循环期间增减迭代序列的成员
>>> arr=[4, 4, 9, 7, 7] >>> for i,a in enumerate(arr): arr.pop(i) print(i,a) 4 0 4 ...
- Python动态展现之一
首先: def f(): print('first') def g(): f() g() def f(): print('second') g() 结果: >>> first sec ...