split()方法失败

时间:2009-05-28 20:20:16

标签: java split

我正在阅读具有以下格式的文本文件:

Room1*Exposition*Work 1 | Work 2 | Work 3 | Work n
Room2*Exposition*Obra 1 | Work 2 | Work 3 | Work n

使用以下内容:

try {

            String path="contenidoDelMuseo.txt";
            File myFile = new File (path);
            FileReader fileReader = new FileReader(myFile);

            BufferedReader reader = new BufferedReader(fileReader);

            String line = null;

            while ((line=reader.readLine())!=null){

            String [] fields = line.split("\\*");

}

每次尝试访问fields[1]时都会抛出IndexOutOfBoundsException。为什么呢?

编辑:该类的整个代码是

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

/*
 * Buscar.java
 *
 * Created on 23/04/2009, 06:22:54 PM
 */

package interfaces;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
 *
 * @author Alirio
 */
public class Buscar extends javax.swing.JFrame {

    static ArrayList<String>obras = new ArrayList<String>();
    static ArrayList<String>salas = new ArrayList<String>();
    static ArrayList <String> exposiciones = new ArrayList <String>();

    /** Creates new form Buscar */

    public Buscar() {
        initComponents();

        try {

            String ruta="contenidoDelMuseo.txt";
            File myFile = new File (ruta);
            FileReader fileReader = new FileReader(myFile);

            BufferedReader reader = new BufferedReader(fileReader);

            String line = null;

            while ((line=reader.readLine())!=null){

                System.out.println(line);
            String []camposABuscar = line.split("\\*");
            salas.add(camposABuscar[0]);


            System.out.println(camposABuscar[0]);
            System.out.println(camposABuscar[1]);
            //System.out.println(camposABuscar[1]);
            // exposiciones.add(camposABuscar[1]);

            //String []obrasABuscar = camposABuscar[2].split("\\|");


            /*
            for (int contador =0; contador <obrasABuscar.length; contador++)
            {

                obras.add(obrasABuscar[contador]);
            }*/


            //System.out.print(obras.get(0));
            }

            reader.close();
        }

        catch (IOException ex){
            ex.printStackTrace();

        }





    }

    /** 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() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        Buscatext = new javax.swing.JTextField();
        Criterios = new javax.swing.JComboBox();
        Buscar = new javax.swing.JButton();
        labelBusqueda = new javax.swing.JLabel();
        labelCriterios = new javax.swing.JLabel();
        BotonSalir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(null);

        jPanel2.setBackground(new java.awt.Color(255, 153, 0));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Buscador", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
        jPanel2.setToolTipText("Hola");

        Criterios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-Seleccione-", "Autor", "Sala", "Piso", " " }));

        Buscar.setText("Buscar");
        Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuscarActionPerformed(evt);
            }
        });

        labelBusqueda.setText("Busqueda:");

        labelCriterios.setText("Criterios:");

        BotonSalir.setText("Salir");
        BotonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(labelBusqueda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(Buscatext, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
                .addGap(63, 63, 63)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(labelCriterios)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(Criterios, 0, 179, Short.MAX_VALUE)
                        .addGap(56, 56, 56)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(BotonSalir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(Buscar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                        .addGap(60, 60, 60))))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {Buscar, Criterios});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelBusqueda)
                    .addComponent(labelCriterios))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Buscatext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Criterios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Buscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BotonSalir)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {Buscar, Criterios});

        jPanel1.add(jPanel2);
        jPanel2.setBounds(20, 180, 720, 130);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/LOGOTIPO.jpg"))); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(10, 10, 250, 150);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/iconoconejo.gif"))); // NOI18N
        jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel3MouseClicked(evt);
            }
        });
        jPanel1.add(jLabel3);
        jLabel3.setBounds(710, 0, 50, 50);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/fondos/background_1.jpg"))); // NOI18N
        jLabel2.setText("jLabel2");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(0, 0, 980, 980);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 763, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 619, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

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

    private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        ClaveAdministrador CA= new ClaveAdministrador();
        CA.setVisible(true);
}                                    

    private void BotonSalirActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        InterfazSeleccion A= new InterfazSeleccion();
        A.setVisible(true);
        this.setVisible(false);
}                                          

    private void BuscarActionPerformed(java.awt.event.ActionEvent evt) {

        String s = Buscatext.getText ();



    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Buscar().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton BotonSalir;
    private javax.swing.JButton Buscar;
    private javax.swing.JTextField Buscatext;
    private javax.swing.JComboBox Criterios;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel labelBusqueda;
    private javax.swing.JLabel labelCriterios;
    // End of variables declaration

}

4 个答案:

答案 0 :(得分:3)

我敢打赌,你文件的第一个“行”实际上是空白的,所以你第一次通过循环时拆分什么都不做,因此数组是空的。你可以检查 fields [] 数组的大小,然后才能使用它,如果它的null(或length = 0)移动到下一行。

答案 1 :(得分:1)

我用你的数据运行代码。它起作用了......

答案 2 :(得分:1)

我在给定文本上尝试了拆分方法。我试着像你自己一样分裂它。一切都很完美。当您从文本文件中读取时,我认为存在问题。我建议你先检查一下。

答案 3 :(得分:1)

这可能是一个愚蠢的答案,但文件末尾是否包含一个空行?

此外,尝试在分割之前打印出您正在分割的线条。这样你就可以看到代码实际上要分割的字符串。