1、简单记事本的java实现代码:
package com.day22;2、dos命令行下的一些jar命令:jar -cvfm jar文件名称(后缀要有.jar) 主类的配置文件
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class SimpleNotepad {
private Frame f;
private MenuBar bar;
private Menu file;
private MenuItem open,save,exit;
private TextArea ta;
private File file0;
public SimpleNotepad()
{
init();
}
void init()
{
f = new Frame("SimpleNotepad");
f.setBounds(300,100,500,400);
bar = new MenuBar();
file = new Menu("文件");
open = new MenuItem("打开");
save = new MenuItem("保存");
exit = new MenuItem("退出");
ta = new TextArea();
bar.add(file);
file.add(open);
file.add(save);
file.add(exit);
f.setMenuBar(bar);
f.add(ta);
myEvent();
f.setVisible(true);
}
void myEvent()
{
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(f,"打开",FileDialog.LOAD);
fd.setVisible(true);
String dirPath = fd.getDirectory();
String fileName = fd.getFile();
if( dirPath==null || fileName==null )
return;
ta.setText("");
file0 = new File(dirPath,fileName);
BufferedReader br = null;
try
{
FileInputStream fis = new FileInputStream(file0);
br = new BufferedReader(new InputStreamReader(fis));
String str = null;
while( (str = br.readLine()) != null)
{
ta.append(str+"\r\n");
}
}
catch(IOException ex)
{
throw new RuntimeException("读取文件失败!");
}
finally
{
try
{
if( br != null )
br.close();
}
catch(IOException ea)
{
throw new RuntimeException("关闭资源失败!");
}
}
}
});
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if( file0 == null )
{
FileDialog fd= new FileDialog(f,"保存",FileDialog.SAVE);
fd.setVisible(true);
String dirPath = fd.getDirectory();
String fileName = fd.getFile();
if( dirPath==null || fileName==null )
return;
file0 = new File(dirPath,fileName);
}
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file0)));
bw.write(ta.getText());
}
catch(IOException ex)
{
throw new RuntimeException("写入文件失败!");
}
finally
{
try
{
if( bw != null )
bw.close();
}
catch(IOException ea)
{
throw new RuntimeException("关闭资源失败!");
}
}
}
});
}
public static void main(String[] args) {
new SimpleNotepad();
}
}
另外,需注意的是配置主类文件时,要注意它的格式,注意空格和换行。