需求分析:
- 獲得文本名稱
- 實(shí)現(xiàn)尾部追加功能
- 實(shí)現(xiàn)覆蓋式添加數(shù)據(jù)
- 刪除數(shù)據(jù)
- 獲取光標(biāo)位置
- 在特定光標(biāo)位置處添加數(shù)據(jù)
- 查找特定字符串在主串中第一次出現(xiàn)的位置
- 統(tǒng)計(jì)文本文件內(nèi)出現(xiàn)的數(shù)字,漢字陪白,英文字母拗引,特殊字符的個(gè)數(shù)串塑,及總的字符個(gè)數(shù)
開發(fā)環(huán)境:
windows7 + Eclipse luna + WindowsBuilder插件
代碼實(shí)現(xiàn):
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("您打開的文件的內(nèi)容是:" + 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("您打開的文件的內(nèi)容是:" + 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("您打開的文件的內(nèi)容是:" + 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("您打開的文件的內(nèi)容是:" + 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("您打開的文件的內(nèi)容是:" + fileContent);
String p = taEdit.getText().toString().trim();
taShow.setText(fileContent+"\n\n"+"您查找的字符串第一次出現(xià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("定點(diǎn)的數(shù)據(jù)插入成功執(zhí)行!");
}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("刪除操作已完成蛔垢,請(qǐng)到相應(yīng)路徑下查看!");
} 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 = "數(shù)據(jù)信息統(tǒng)計(jì)結(jié)果如下:" + "\n" + "漢字?jǐn)?shù)目:";
flag += new Total().chineseCount;
flag += "\n英文字母個(gè)數(shù):";
flag += new Total().englishCount;
flag += "\n特殊字符個(gè)數(shù):";
flag += new Total().numberCount;
flag += "\n總的字符個(gè)數(shù)為:"
+ (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();
}
}
}
}
下面解釋一下為什么沒有做好注釋合作說明文檔焙压,因?yàn)槲易鲎⑨屪龅揭话氲臅r(shí)候三娩,出現(xiàn)了一點(diǎn)事故庵芭,導(dǎo)致沒有來得及保存的文件丟失了,所以雀监,請(qǐng)大家謹(jǐn)記双吆,時(shí)刻記得保存編輯的被容,否則后果真的很嚴(yán)重会前。
代碼追補(bǔ)解釋好乐,下面的代碼塊是我程序里面做的不好的,違背了代碼的復(fù)用性原則回官,請(qǐng)予以為戒:
代碼塊1:
//代碼的作用就是實(shí)現(xiàn)對(duì)特定的文件進(jìn)行讀取曹宴,并存入到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("您打開的文件的內(nèi)容是:" + fileContent);
CursorPosition = e.getDot();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
代碼塊2:
//代碼實(shí)現(xiàn)了向特定的文件內(nèi)追加數(shù)據(jù)歉提,若想要覆蓋式追加,把參數(shù)true去掉即可区转,默認(rèn)為覆蓋式添加數(shù)據(jù)
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:
在統(tǒng)計(jì)模塊中:
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 = "數(shù)據(jù)信息統(tǒng)計(jì)結(jié)果如下:" + "\n" + "漢字?jǐn)?shù)目:";
flag += new Total().chineseCount;
flag += "\n英文字母個(gè)數(shù):";
flag += new Total().englishCount;
flag += "\n特殊字符個(gè)數(shù):";
flag += new Total().numberCount;
flag += "\n總的字符個(gè)數(shù)為:"
+ (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;
/**
* 分別統(tǒng)計(jì)出其中字符串中漢字,英文字母废离,數(shù)字侄泽,其他字符數(shù)量
* @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]";// 數(shù)字
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("漢字?jǐn)?shù):" + chineseCount);
System.out.println("英文數(shù):" + englishCount);
System.out.println("數(shù)字?jǐn)?shù):" + numberCount);
System.out.println("特殊字符:" + (str.length() - (chineseCount + englishCount + numberCount)));
}
}
好了,下面是程序運(yùn)行后得到的界面蜻韭,在此我要聲明的是悼尾,程序仍然存在一些bug,表現(xiàn)在獲得光標(biāo)位置時(shí)的java.lang.IllegalStateException: Attempt to mutate in notification異常肖方,主要還是線程相關(guān)闺魏,如果博友能解決,還望不吝賜教
能力有限俯画,希望和大家一起進(jìn)步析桥,一同提高!
接下來的是我從網(wǎng)上找到的一份用C語言實(shí)現(xiàn)的簡易的文本編輯器的實(shí)現(xiàn)艰垂,個(gè)人認(rèn)為較之泡仗,我的簡直就是太菜了,現(xiàn)在將代碼貼出來猜憎,希望這篇C語言的經(jīng)典能讓更多的人知曉:
#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};/*對(duì)應(yīng)處理函數(shù)*/
int modified=0,/*正文被修改標(biāo)志*/
last;/*當(dāng)前正文行數(shù)*/
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++;/*掠過命令符娩怎,指向參數(shù)*/
(*comfun[j/2])();/*執(zhí)行對(duì)應(yīng)函數(shù)*/
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]); /* 釋放內(nèi)存 */
exit(0);
}
void insert()
{
int k,m,i;
sscanf(chpt,"%d%d",&k,&m); /* 讀入?yún)?shù) */
if(m<0||m>last||last+k>=MAXLINE)/* 檢查參數(shù)合理性 */
{
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; /* 修正正文行數(shù) */
modified=1; /* 正文被修改 */
}
void delete()
{
int i,j,m,n;
sscanf(chpt,"%d%d",&m,&n); /* 讀入?yún)?shù) */
if(m<=0||m>last||n<m) /* 檢查參數(shù)合理性 */
{
printf("Error!\n");
return;
}
if(n>last)
n=last; /* 修正參數(shù) */
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; /* 修正正文行數(shù) */
modified=1; /* 正文被修改 */
}
void replace()
{
int k,m,n,i,j;
sscanf(chpt,"%d%d%d",&k,&m,&n); /* 讀入?yún)?shù) */
if(m<=0||m>last||n<m||last-(n-m+1)+k>=MAXLINE)/* 檢查參數(shù)合理性 */
{
printf("Error!\n");
return;
}
/* 先完成刪除 */
if(n>last)
n=last; /* 修正參數(shù) */
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; /* 修正正文行數(shù) */
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"); /* 如不存在胰柑,則創(chuàng)建文件 */
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;
}