簡體   English   中英

如何在Java中讀取和拆分文件的內容?

[英]How to read and split the contents of file in Java?

我如何在 : 之后獲取信息並在拆分面板中向用戶顯示它們

Title: Randon Number Graph
Xlabel: Possible Range
Ylabel: Typical Value
start: -100.5
interval: 20.25
40, 90.2, 101.654, 60.2, 90.2, 100.2, 95

我已經展示了文件的設置以及我迄今為止創建的代碼。

@SuppressWarnings("serial") 公共類 BasicGUI 擴展 JFrame {

private JPanel contentPane;
public JTextArea inputTextArea;
public JTextArea outputGraphicalArea;
String Title;
String Xlabel;
String Ylabel;
int Start;
int Interval;
int Data;

JSplitPane splitPane;

// 創建框架。

public BasicGUI() {
    // Set the menu bar 
    createMenuBar();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane = new JPanel();
    // This creates the border around the split panel 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    //
    contentPane.setLayout(new BorderLayout(0, 0));



    // the split panel include two TextArea one for and the other one for displaying graphical data


    inputTextArea = new JTextArea();
    outputGraphicalArea = new JTextArea();

    // put two TextArea to JScrollPane so text can be scrolled when too long
    JScrollPane scrollPanelLeft = new JScrollPane(inputTextArea);
    JScrollPane scrollPanelRight = new JScrollPane(outputGraphicalArea);

    // put two JScrollPane into SplitPane 
    JSplitPane applicationpanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            scrollPanelLeft, scrollPanelRight);

    applicationpanel.setOneTouchExpandable(true);

    // Add the panel to the frame and also to centre the panel
    contentPane.add(applicationpanel, BorderLayout.CENTER);
    // This is to size the panel so they are both equal
    applicationpanel.setResizeWeight(0.5); 


    // The application panel settings 
    setContentPane(contentPane);
    // This to to set the title of the application panel which is " Requirement 1 + 2 "
    setTitle(" Requirement 1 + 2 ");
    // This is the size that I ha set for the application panel which is width, length
    setSize(350, 250);
    // This allows the application panel to open freely on the centre of the screen 
    setLocationRelativeTo(null);
    // This is to close the application panel when the user has clicked on the close button 
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Actually show 
    setVisible(true);


}
private void createMenuBar() {

    JMenuBar menubar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenu helpMenu = new JMenu("Help");
    /////////////////////////////////////////////    
   JMenuItem aboutMenu = new JMenuItem("About");
   aboutMenu.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent event)
         {
            if (dialog == null) // first time
            dialog = new AboutDialog(BasicGUI.this);
            dialog.setVisible(true); // pop up dialog
         }
      });                
    ImageIcon iconLoad = new ImageIcon("load_icon.png");
    JMenuItem loadMi = new JMenuItem("Load", iconLoad);


 // Create a file chooser that opens up as an Open dialog
    loadMi.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        JFileChooser chooser = new JFileChooser();
        int status = chooser.showOpenDialog(null);
        if (status != JFileChooser.APPROVE_OPTION)
            inputTextArea.setText("No File Chosen");
         else
         {
             File file = chooser.getSelectedFile();
             Scanner scan = null;
            try {
                scan = new Scanner(file);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             String info = "";
             while (scan.hasNext())
                info += scan.nextLine() + "\n";


             inputTextArea.setText(info);
         }


    }
    });

   ImageIcon iconSave = new ImageIcon("save_icon.png");
   JMenuItem saveMi = new JMenuItem("Save", iconSave);


   /////////////////////////////////////////////
 ImageIcon iconExit = new ImageIcon("exit_icon.png");
 JMenuItem exitMi = new JMenuItem("Exit", iconExit);

   exitMi.setMnemonic(KeyEvent.VK_E);
   //This creates a note for the user when they hover over the Exit button  
   exitMi.setToolTipText("Exit application");

   exitMi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
       ActionEvent.CTRL_MASK));
   ///////////////////////////////////////////////
   exitMi.addActionListener(new ActionListener() {
       @Override
       // As soon as the user has selected to exit  overrides the application and closes the application panel for the user 
       public void actionPerformed(ActionEvent event) {
           System.exit(0);
       }
});


   ////////////////////////////////////////
   fileMenu.add(loadMi);
   fileMenu.add(saveMi);
   ////////////////////////////////////////
   fileMenu.addSeparator();
   ////////////////////////////////////////
   fileMenu.add(exitMi);
   ////////////////////////////////////////
   menubar.add(fileMenu);
   menubar.add(aboutMenu);
   ////////////////////////////////////////
   menubar.add(Box.createHorizontalGlue());
   ////////////////////////////////////////
   menubar.add(helpMenu);
   ///////////////////////////////////////
   setJMenuBar(menubar);  
}


   private AboutDialog dialog;
}


 // dialog that displays a message and waits for the user to click the OK button.

@SuppressWarnings("serial")
class AboutDialog extends JDialog
{
   public AboutDialog(JFrame owner)
   {
      super(owner, "About DialogBox", true);

      // add HTML label because its a dialog box so defiantly will need HTML 

      add(
              new JLabel
              (
                    "<html><h1><i>Requirement 1 –  Basic GUI creation </i></h1><hr>The first requirement for this assignment is to implement the basic Graphical User Interface (GUI) as an initial prototype. At this point the application will be an “empty shell”, with very limited functionality. However it should consist of an application frame, a menu bar and a main application panel split into two halves.  One half should be capable of displaying a textual representation of the file being processed, and the other will (eventually) show the graphical representation of that data<hr>The text panel should be capable of showing all information read from the text file (see requirement 2), but in an aesthetically pleasing manner. You may choose to use labels and associated values to show heading information, such as the 'Title'.  The data should be shown within some kind of text window (with scrollbars when required).<hr>The menu bar should consist of a 'File' and 'Help' menu.  The File menu should include options for loading, saving and exiting the application.  The 'Help' menu should contain an option for showing a dialogue box which identifies information about the application. At this point however only the 'Exit' and 'About' options need to work<hr>The application should be designed so that it uses layout managers where appropriate, and can be sensibly resized by the user.  The menu options should also include short-cuts and icons where appropriate.<hr><h1><i>Requirement 2 –  Loading and parsing </i></h1><hr>Once a basic GUI is available the next requirement is to add the ability to actually load, parse and display the data. The 'File | Load' option should show a file open dialogue allowing selection of a data file.  Once this is done the file should be opened, read and parsed.  This process should involve validating the contents of the file against the expected format. If something is missing then an error message should be shown to the user in the form of a dialogue box.<hr>Once the file information has been loaded and parsed, the information should be displayed within the appropriate textual representation elements of the GUI (as developed as part of requirement 1).</html>"  
              ),
              BorderLayout.CENTER);

      // OK button closes the dialog

      JButton ok = new JButton("Ok");
      ok.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               setVisible(false);
            }
         });

      // add  button to bottom part of the dialog box

      JPanel panel = new JPanel();
      panel.add(ok);
      add(panel, BorderLayout.SOUTH);

      setSize(550, 750);

    /////////////////////////////////////////////
  ImageIcon iconExit = new ImageIcon("exit_icon.png");
  JMenuItem exitMi = new JMenuItem("Exit", iconExit);

    exitMi.setMnemonic(KeyEvent.VK_E);
    //This creates a note for the user when they hover over the Exit button  
    exitMi.setToolTipText("Exit application");

    exitMi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
        ActionEvent.CTRL_MASK));
    ///////////////////////////////////////////////
    exitMi.addActionListener(new ActionListener() {

        // As soon as the user has selected to exit  overrides the application and closes the application panel for the user 
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
 });   
}

您可以使用 Java 文件屬性 支持“:”作為屬性名稱/值的分隔符。

例子:

Properties prop = new Properties();
try {
    prop.load(YourClass.class.getClassLoader().getResourceAsStream("filename.properties"));
    System.out.println(prop.getProperty("Title"));
} 
catch (IOException ex) {}

將一堆單獨的問題合並為一個的好方法。

要讀取文件...

Scanner scanner = new Scanner( new File("*filename*"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close() // Put this call in a finally block

現在,要得到每一行..

// split on "\n" to get the lines
String[] lines = text.split("\n");

如果一行包含“:”,則將其拆分為“:”。 index [0] 將包含Title , index [1] 將包含Random Number Graph

當然可以有更好的方法來做到這一點。 嗯……以后不要把 3-4 個問題歸為 1 個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM