【问题标题】:How can I actually use delimeter?我如何实际使用分隔符?
【发布时间】:2012-08-14 05:11:39
【问题描述】:

如何在java中实际使用分隔符,这是示例data.dat文件

   1 yuri
   2 fisher
   3 McMillan
   4 price
   5 soap

我怎样才能只获取文件中每一行的第一个数字并使用 useDelimiter() 方法

我该如何处理这段代码

Scanner src = new Scanner(fin);
                                 src.useDelimiter(" \n");
                                DefaultListModel model = new DefaultListModel();
                                while (src.hasNext()) {
                                String lol = src.nextLine();
                                model.addElement(lol);
                                }
                                list.setModel(model);
                                } 
                                });

这是整个代码.. 嗯.. 文件中并不总是“lol”,我稍后会更改它

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jfetizanan
 */
@SuppressWarnings("serial")
public class IOtestForm extends javax.swing.JFrame {

    /**
     * Creates new form IOtest
     */
    public IOtestForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        input0 = new javax.swing.JTextField();
        load = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(list);
        DefaultListSelectionModel m = new DefaultListSelectionModel();
        m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        m.setLeadAnchorNotificationEnabled(false);
        list.setSelectionModel(m);
        list.addListSelectionListener(new ListSelectionListener() {
            @Override
        public void valueChanged(ListSelectionEvent e) {
        int selected[] = list.getSelectedIndices();
        for (int i = 0; i < selected.length; i++) {
        String element = (String) list.getModel().getElementAt(selected[i]);
        input0.setText(element);
        }}});

        load.setText("Load");
        load.addActionListener(new ActionListener() {
                            @Override
            @SuppressWarnings("unchecked")
                            public void actionPerformed(ActionEvent e) {
                                 FileReader fin = null;
                            try {
                                 fin = new FileReader("data.dat");
                                } catch (FileNotFoundException ex) {
                                   Logger.getLogger(IOtestForm.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                Scanner src = new Scanner(fin);
                                src.useDelimiter("\\s*lol\\s*");
                                DefaultListModel model = new DefaultListModel();
                                while (src.hasNext()) {
                                String lol = src.next();
                                model.addElement(lol);
                                }
                                list.setModel(model);
                                } 
                                });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(input0)
                    .addComponent(load, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addComponent(load)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(input0, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(94, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IOtestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new IOtestForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField input0;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList list;
    private javax.swing.JButton load;
    // End of variables declaration
}

【问题讨论】:

    标签: java swing list io jlist


    【解决方案1】:

    您可以使用src.useDelimiter("\\s*lol\\s*")。解析示例见http://ideone.com/kZUL6

    【讨论】:

    • 看看我的代码,或者你可以实际运行它.. Uhhmm...是的!你帮我只显示了数字,但它也显示了文本区域中没有大声笑的数字
    • 那是因为它匹配 '\n' 字符,当您使用分隔符时,这是预期的 - 请参阅ideone.com/Pkc8r
    【解决方案2】:

    让我们从基础开始

    要加载文件,您可以这样做

    Scanner src = new Scanner(is);
    while (src.hasNext()) {
    
        int line = src.nextInt();
        String value = src.next();
    
        System.out.println(line + " = " + value);
    
    }
    

    现在,我们真正需要的是某种方法来对这些信息进行建模。更好的解决方案是创建某种类型的对象来表示这些信息,以便于管理。

    类似

    public class LineOfText {
    
        private int line;
        private String value;
    
        public LineOfText(int line, String value) {
            this.line = line;
            this.value = value;
        }
    
        public int getLine() {
            return line;
        }
    
        public String getValue() {
            return value;
        }
    
    }
    

    好的,那么我们需要将文件中的属性应用到它。

    Scanner src = new Scanner(is);
    while (src.hasNext()) {
    
        int line = src.nextInt();
        String value = src.next();
    
        LineOfText lot = new LineOfText(line, value);
    
    }
    

    我们可以将其添加到您已经创建的ListModel

    model.addElement(lot);
    

    现在,如果我们在 UI 上显示它,它看起来不是很漂亮。我们真正需要的是某种更有效地“渲染”文本的方法。

    类似

    public class LineOfTextListCellRenderer extends DefaultListCellRenderer {
    
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    
            if (value instanceof LineOfText) {
    
                value = ((LineOfText)value).getLine();
    
            }
    
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    
        }
    
    }
    

    应该这样做。我们需要将此渲染器应用到您之前创建的列表中。

    list.setListCellRenderer(new LineOfTextListCellRenderer());
    

    现在,如果我们在 UI 上显示它,我们应该只看到列表中的行号。

    接下来,我们需要一些方法来检测选择的变化。为此,我们需要ListSelectionListener

    list.addListSelectionListener(new ListSelectionListener() {
    
        @Override
        public void valueChanged(ListSelectionEvent e) {
    
            Object item = list.getSelectedItem();
            if (item != null && item instance of LineOfText) {
                ListOfText lot = (LineOfText)lot;
                // Now we have access to the text value
                // Simply use "setText" on the text area to apply it
    
                textArea.setText(lot.getValue());
    
                // Remember, "textArea" should be replaced with the name
                // of your text area
            }
    
        }
    
    });
    

    现在你明白为什么这是一个单独的问题了;)

    【讨论】:

      【解决方案3】:

      另一种解决方案是在空格处分割每一行:

      String[] split = lol.trim().split("\\s+");
      

      然后您应该会在每个 split[0] 看到第一个数字。

      【讨论】:

        【解决方案4】:

        将分隔符设置为\\s*lol\\s*

        public static void main(String[] args)
        {
            String myString = "1 lol\n2 lol\n3 lol\n4 lol\n5 lol";
            System.out.println(myString);
            Scanner scanner = new Scanner(myString);
            scanner = scanner.useDelimiter("\\s*lol\\s*");
            while(scanner.hasNext())
            {
                System.out.println(scanner.next());
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-01-25
          • 1970-01-01
          • 1970-01-01
          • 2012-02-19
          • 1970-01-01
          • 1970-01-01
          • 2017-10-31
          相关资源
          最近更新 更多