你要的关键程序代码:。(源文件超过10000字,无法粘全在这,要的话,加我)if(e.getActionCommand()=="保存"||e.getActionCommand()=="保存为")
{
JFileChooser chooser=new JFileChooser(); //创建文件选择对话框
int result=chooser.showSaveDialog(frame);
if(result==JFileChooser.APPROVE_OPTION)
{
try
{
FileWriter fout = new FileWriter(chooser.getSelectedFile()); //向磁盘中写文件
fout.write(jtextpane.getText()+"\r\n");
fout.close();
}
catch (IOException ioex)
{
}
}
}执行效果:
可以通过“FileOutputStream”创建文件实例,之后过“OutputStreamWriter”流的形式进行存储,举例:
OutputStreamWriter pw = null;//定义一个流
pw = new OutputStreamWriter(new FileOutputStream(“D:/test.txt”),"GBK");//确认流的输出文件和编码格式,此过程创建了“test.txt”实例
pw.write("我是要写入到记事本文件的内容");//将要写入文件的内容,可以多次write
pw.close();//关闭流
解释:文件流用完之后必须及时通过close方法关闭,否则会一直处于打开状态,直至程序停止,增加系统负担。
JTextArea jta;//编辑框boolean wasSaved=true;//当前文件是否已保存…………public void saveFile(File f){//保存文件
FileWriter fw=null;
try {
fw=new FileWriter(f);
fw.write(jta.getText());
fw.flush();
wasSaved=true;
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(fw!=null)try {fw.close();} catch (IOException e) {}
}
}
public void openFile(File f){//打开文件
FileReader fr=null;
BufferedReader br=null;
jta.setText("");
try {
fr=new FileReader(f);
br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null){
jta.append(str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
}
wasSaved=true;
if(br!=null)try{br.close();}catch(IOException e){}
if(fr!=null)try{fr.close();}catch(IOException e){}
}
}