【问题标题】:How to save a file in a text editor?如何在文本编辑器中保存文件?
【发布时间】:2017-02-16 06:34:20
【问题描述】:

这段代码创建了一个小应用程序,它最初是一个基本的文本编辑器,我添加了一个下拉文件菜单,在每个编辑器中都很明显,它包括“新建”、“打开”、“保存”和“保存”等功能作为'。

我不知道如何添加保存在现有文件和新文件中的功能。

import java.io.*;  
import java.awt.event.*;  
import javax.swing.*;    
import java.io.IOException;
import java.nio.file.StandardOpenOption;

public class Editor implements ActionListener
{    

    boolean updateStatus;
    Editor Jedtr;
    boolean saved;  
    boolean newFileFlag;  
    String fileName;    
    static File fileRef;  


    JFrame f;    
    JMenuBar mb;    
    JMenu file,edit,help;    
    JMenuItem cut,copy,paste,selectAll,NewFile,Open,Save,SaveAs;    
    JTextArea ta;  


    Editor(){ 


        saved=true;  
        newFileFlag=true;  
        fileName=new String("Untitled");  
        fileRef=new File(fileName);  

        Open=new JMenuItem("Open File");    
        Open.addActionListener(this);            
        file=new JMenu("File");    
        file.add(Open);             
        mb=new JMenuBar();    
        f=new JFrame();    
        cut=new JMenuItem("Cut");    
        copy=new JMenuItem("Copy");    
        paste=new JMenuItem("Paste");    
        selectAll=new JMenuItem("Select All");    

        /////////////////////////////////////////////////////////////////////////////////

        NewFile =new JMenuItem("New");
        Open=new JMenuItem("Open");
        Save=new JMenuItem("Save");
        SaveAs=new JMenuItem("Save As");

        ///////////////////////////////////////////////////////////////////////////////////

        cut.addActionListener(this);    
        copy.addActionListener(this);    
        paste.addActionListener(this);    
        selectAll.addActionListener(this);

        /////////////////////////////////////////////////////////////////////////////////////

        NewFile.addActionListener(this);
        Open.addActionListener(this);
        Save.addActionListener(this);
        SaveAs.addActionListener(this);

        //////////////////////////////////////////////////////////////////////////////////

        mb=new JMenuBar();    
        file=new JMenu("File");    
        edit=new JMenu("Edit");    
        help=new JMenu("Help");     
        file.add(NewFile);file.add(Open);file.add(Save);file.add(SaveAs);    
        edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);    
        mb.add(file);mb.add(edit);mb.add(help);    

        ///////////////////////////////////////////////////////////////////////////////////////

        ta=new JTextArea();    
        ta.setBounds(5,5,1200,1200);    
        f.add(mb);f.add(ta);    
        f.setJMenuBar(mb);  
        f.setLayout(null);    
        f.setSize(800,400);    
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }     




    /////////////////////////////Action performed/////////////////////////////////////////////////


    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource()==cut)                 
            ta.cut();                                // to cut text.
        else if(e.getSource()==paste)
            ta.paste();                             // to paste text. 
        else if(e.getSource()==copy)
            ta.copy();                              // to copy text.
        else if(e.getSource()==selectAll)
            ta.selectAll();                        // to select text. 
        else if(e.getSource()==Open)
        {
            JFileChooser fc=new JFileChooser();
            int i=fc.showOpenDialog(f);
            if(i==JFileChooser.APPROVE_OPTION)
            {
                File f=fc.getSelectedFile();
                String filepath=f.getPath();
                try
                {
                    BufferedReader br=new BufferedReader(new FileReader(filepath));
                    String s1="",s2="";
                    while((s1=br.readLine())!=null)
                    {
                        s2+=s1+"\n";
                    }
                    ta.setText(s2);
                    br.close();
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }                                       //to open an existing file
        else if(e.getSource() == NewFile)
        {
            JFileChooser fc=new JFileChooser();
            int j=fc.showOpenDialog(f);
            if (j==JFileChooser.CUSTOM_DIALOG);

            System.out.println("New File");

            File file = new File("C:\\Android\\.txt");

            boolean result;
            try {
                // create a new file
                result = file.createNewFile();
                // test if successfully created a new file
                if(result){
                    System.out.println("Successfully created "+file.getAbsolutePath());

                }
                else{
                    System.out.println("Filed creating "+file.getAbsolutePath());
                }
            }
                catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
    }                                            // to create a new file.

            else if(e.getSource()== SaveAs)
            {                                  // what to specify here?
                }



            else if(e.getSource()==Save)
            {                                 // what to specify here?
            }
}




                /*private Object SaveAs(File temp)
{
    // TODO Auto-generated method stub
    return null;
}



///////////////////////////////////////////////////////////////////////////////////////////////


private void updateStatus(File temp, boolean b)
{
    // TODO Auto-generated method stub

}*/
                boolean isSave()
                {
                    return saved;}  

                void setSave(boolean saved)
                {
                    this.saved=saved;
                }

                String getFileName()
                {
                    return new String(fileName);
                }

                void setFileName(String fileName)
                {
                    this.fileName=new String(fileName);
                }  

                ////-------File-------////////

                //public class File implements ActionListener{}

                ////-------File-------////////

                /*public void actionPerformedf(ActionEvent O) {    
if(O.getSource()==Open){    
    JFileChooser fc=new JFileChooser();    
    int i=fc.showOpenDialog(f);    
    if(i==JFileChooser.APPROVE_OPTION){    
        File f=fc.getSelectedFile();    
        String filepath=f.getPath();    
        try{  
        BufferedReader br=new BufferedReader(new FileReader(filepath));    
        String s1="",s2="";                         
        while((s1=br.readLine())!=null){    
        s2+=s1+"\n";    
        }    
        ta.setText(s2);    
        br.close();    
        }catch (Exception ex) 
        {
            ex.printStackTrace();          
        }
    }
    }
    }*/    

                public static void main(String[] args) {    

                    new Editor(); 

                }    
            }

【问题讨论】:

  • 1) 请学习常见的 Java 命名法(命名约定 - 例如EachWordUpperCaseClassfirstWordLowerCaseMethod()firstWordLowerCaseAttribute,除非它是 UPPER_CASE_CONSTANT)并始终如一地使用它。 2) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
  • .. 3) 使用逻辑一致的缩进代码行和块的形式。缩进是为了让代码流更容易理解! 4) 编辑器加载文本的方式可以更简单,详见JTextComponent.read(Reader, Object)5) 将文本保存到文件,见JTextComponent.write(Writer) ..
  • 6) 要获得更多帮助,您需要更具体地说明卡在哪里,这个问题就目前而言“过于宽泛”。

标签: java swing file io jtextarea


【解决方案1】:

小程序无法访问本地文件系统。这将被修复 在不久的将来,小程序将根本不存在。感谢甲骨文!

【讨论】:

  • 虽然“applet”被提及两次,但代码显示了一个应用程序。我已经对问题进行了一些清理(对其进行了编辑)以使其更加清晰。