- //需要的变量
-
private String myTitle ;
-
private String oldStr;//保存记事本中旧的数据,判断文件是否改变
-
//文件,文件流相关的变量
-
private JFileChooser fileChooser = new JFileChooser();
-
private FileFilter filter = new FileNameExtensionFilter("记事本文件(txt)","TXT");
-
private FileFilter sFilter = new FileNameExtensionFilter("记事本文件(txt)","TXT","*");
-
private File selectedFile ;
-
private FileReader fr;
-
private FileWriter fw;
-
private BufferedReader bufr;
-
1.打开文件
- private void openFile(){
-
-
myJta.setText("");//清空此前数据
-
fileChooser.setFileFilter(filter);
-
-
int i = fileChooser.showOpenDialog(getContentPane());
-
if(i==JFileChooser.APPROVE_OPTION){
-
selectedFile = fileChooser.getSelectedFile();
-
myTitle = selectedFile.getName();
-
setTitle(myTitle+"-记事本");
-
try {
-
fr = new FileReader(selectedFile);
-
bufr = new BufferedReader(fr);
-
String tempS ="";
-
while((tempS=bufr.readLine())!=null){
-
myJta.append(tempS+"\r\n");
-
}
-
bufr.close();
-
fr.close();
-
} catch (Exception e1) {
-
// TODO Auto-generated catch block
-
e1.printStackTrace();
-
}
-
oldStr = myJta.getText();
-
}
-
}
2.新建文件
- private void newFile(){
-
int i = checkEdited();
-
if(i == JOptionPane.OK_OPTION){
-
if("无标题 -记事本".equals(myTitle)){
-
saveOFile();
-
}
-
else{
-
saveFile();
-
}
-
myTitle = "无标题 -记事本";
-
setTitle(myTitle);
-
myJta.setText("");//清空此前数据
-
}else if(i == JOptionPane.NO_OPTION){
-
myTitle = "无标题 -记事本";
-
setTitle(myTitle);
-
myJta.setText("");//清空此前数据
-
}else if(i==JOptionPane.CANCEL_OPTION){
-
return;
-
}
-
}
3.保存文件
- // save file function
-
private void saveFile(){
-
// try{
-
// fw = new FileWriter(selectedFile);
-
// buwr = new BufferedWriter(fw);
-
// PrintWriter prwr = new PrintWriter(buwr);
-
// prwr.write(myJta.getText());
-
// prwr.close();
-
// buwr.close();
-
// fw.close();
-
// }catch(Exception e1){
-
// e1.printStackTrace();
-
// }
-
//用文件输出流,在换行时,发生错误
-
Document myDoc = myJta.getDocument();
-
DefaultEditorKit kit = new DefaultEditorKit();
-
try {
-
fw = new FileWriter(selectedFile);
-
kit.write(fw,myDoc,0,myDoc.getLength());
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
-
}
其中,用文件输出流时,总是换行时,如果用txt打开,会发现有乱码,换行处。
4.另存为
- // save as function
-
private void saveOFile(){
-
fileChooser.setFileFilter(sFilter);
-
int i = fileChooser.showSaveDialog(getContentPane());
-
if(i==JFileChooser.APPROVE_OPTION){
-
selectedFile = fileChooser.getSelectedFile();
-
myTitle = selectedFile.getName();
-
-
if (selectedFile.exists())
-
{
-
int overwriteSelect = JOptionPane.showConfirmDialog(this,
-
"文件" + myTitle + "已存在,是否覆盖?",
-
"是否覆盖?",
-
JOptionPane.YES_NO_OPTION,
-
JOptionPane.WARNING_MESSAGE);
-
if (overwriteSelect != JOptionPane.YES_OPTION)
-
{
-
return;
-
}
-
}
-
// 如果文件不是以".txt"结尾,则提醒补充.txt
-
if (!myTitle.endsWith("txt"))
-
{
-
JOptionPane.showMessageDialog(this, "请以.txt结尾", "后缀", JOptionPane.DEFAULT_OPTION);
-
myTitle = "无标题 -记事本";
-
return;
-
}
-
setTitle(myTitle+"-记事本");
-
saveFile();
-
}
-
}
阅读(10376) | 评论(0) | 转发(0) |