tags:

views:

200

answers:

4

I'm reading a text file with the following format:

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

Using the following:

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("\\*");

}

An IndexOutOfBoundsException is thrown each time I try to access fields[1]. Why?

Edit: the whole code for the class is

/*
 * 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

}
+1  A: 

I ran the code with your data. It worked...

daveb
Same thing here.
Valentin Rocher
+1  A: 

I tried your the split method on your given text. I tried splitting it like you did yourself. Everything worked perfectly. I think there is something wrong when you are reading from your text file. I would suggest that you check that first.

Marco Leung
+1  A: 

This may be a silly answer, but does the file contain a blank line at the end?

Also, try printing out the line you're splitting just before you split it. That way you can see what strings your code is actually trying to split.

Pourquoi Litytestdata
actually, it doesn't have the blank line. I don't get why is this code failing.
omgzor
+3  A: 

I bet the first "line" of your file is actually blank, so your first time through the loop the split does nothing and hence the array is empty. You could just check the size of the fields[] array before attemtping to use it, if its null (or length = 0) move on to the next line.

Gandalf
Thanks. This thing was maddening.
omgzor