0

I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.

This is some of my code:

try {
        FileReader file_to_read = new FileReader(path);
        BufferedReader br1 = new BufferedReader(file_to_read);
    for (int row=0; row < lineNumber; row++) {         
        try {
        //Reads the set and the subject in the text file
        String strSetSubjectLine = br1.readLine();

        //Splits the string of set and subject by using the comma
        String [] names = strSetSubjectLine.split(",");                
        strSetName = names[0];
        strSubjectName = names[1];

        //Finds the line number to see the number of cards in each set
        lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
        lnr2.skip(Long.MAX_VALUE);
        strLineNumber2 = String.valueOf(lnr2.getLineNumber());
        lineNumber2 = Integer.parseInt(strLineNumber2);

    } catch (IOException | NumberFormatException e) {
        strLineNumber2 = "0";
    }           
        //Adds the set name to the set name array
        lblDeckName[row] = new JLabel (strSetName);

        //Adds all buttons that will be used in the layout into a button array
        JButton aryOptions [][] = new JButton [3][lineNumber];

        //Defines and formats the Add Words button
        JButton btnAddWords = new JButton("Add Words"); 
        btnAddWords.setOpaque(false);
        btnAddWords.setContentAreaFilled(false);
        btnAddWords.setBorder(null);
        btnAddWords.setBorderPainted(false);

        //Defines and formats the Play button
        JButton btnPlay = new JButton("Play");
        btnPlay.setOpaque(false);
        btnPlay.setContentAreaFilled(false);
        btnPlay.setBorder(null);
        btnPlay.setBorderPainted(false);

        //Defines and formats the Delete Set button
        JButton btnDelete = new JButton("Delete Set");
        btnDelete.setOpaque(false);
        btnDelete.setContentAreaFilled(false);
        btnDelete.setBorder(null);
        btnDelete.setBorderPainted(false); 

        //Adds each button to the array based on the number of sets
        aryOptions [0][row] = btnAddWords;
        aryOptions [1][row] = btnPlay;
        aryOptions [2][row] = btnDelete;

        //Formats the GridBagLayout (Spaces are for formatting purposes)
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 0;
        gbc.gridy = row;
        layoutBackground.add(lblDeckName[row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 1;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("      "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx =2;
        gbc.gridy = row;
        layoutBackground.add(new JLabel (strSubjectName),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 3;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("                   "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 4;
        gbc.gridy = row;
        layoutBackground.add(new JLabel(strLineNumber2),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 5;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("             |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 6;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[0][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 7;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 8;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[1][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 9;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |  "),gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 10;
        gbc.gridy = row;
        layoutBackground.add(aryOptions[2][row],gbc);

        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridx = 11;
        gbc.gridy = row;
        layoutBackground.add(new JLabel("  |"),gbc);




        //Creates an action event for the delete set button
        btnDelete.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30); 

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Defines new file reader and buffered reader                   
                FileReader file_to_read2 = new FileReader(path);
                BufferedReader br2 = new BufferedReader(file_to_read2);

                //Finds the numerical index of the button that was clicked
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br2.readLine()) != null) {

                    counter ++;
                    if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
                        try {
                            //Finds the name of the set based on what button was clicked
                            String chosenDeck2 = br2.readLine();
                            String [] aryDeleteDeck = chosenDeck2.split(",");
                            deleteDeck = aryDeleteDeck[0];

                            //Creates the path to the file that needs to be deleted
                            Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                            Files.delete(p2);

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        //Reads the deck name based on the button that was clicked
                        String chosenDeck2 = br2.readLine();

                        //Splits the deck name from the subject
                        String [] aryDeleteDeck = chosenDeck2.split(",");            
                        deleteDeck = aryDeleteDeck[0];

                        //Closes the buffered reader and file reader


                        //Gets the file that needs to be deleted
                        Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
                        Files.delete(p1);

                    }
                }
                br2.close();
                file_to_read2.close();
            }
            catch (HeadlessException | IOException | NumberFormatException e) {
                JOptionPane.showMessageDialog(null, e);
            }
        });

        //Creates an action event for the add words button
        btnAddWords.addActionListener((ActionEvent a) -> {
            //Finds the source of the button that was clicked
            String strSource = String.valueOf(a.getSource());
            String strSourceCut1 = strSource.substring(25,30);

            //Finds the index of the button that was clicked
            String [] aryIndex = strSourceCut1.split(",");
            String strIndex = aryIndex[0];

            try {
                //Creates a new file reader and buffered reader
                FileReader file_to_read3 = new FileReader(path);
                BufferedReader br3 = new BufferedReader(file_to_read3);

                //Finds the index value
                int intIndex = Integer.parseInt(strIndex)/16;

                //Creates a counter to count line numbers
                int counter = 0;

                while((br3.readLine()) != null) {
                    //Increases counter value by 1
                    counter ++;
                    if(intIndex == 0)
                    {
                        try {
                            //Reads the set and subject for the 
                            String chosenDeck2 = br3.readLine();

                            //Splits the subject from the set
                            String [] aryDeck = chosenDeck2.split(",");
                            chosenDeck = aryDeck[0];




                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(null, e);
                        }

                    } else if ( counter == intIndex) {
                        String chosenDeck2 = br3.readLine();

                        String [] aryDeck = chosenDeck2.split(",");
                        chosenDeck = aryDeck[0];

                    }

                }
                br3.close();
                file_to_read3.close();
            }
            catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
            //Opens the new words frame
            frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
            s.setVisible(true);
        });


}
} catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);



    }

}

The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.

I am really stuck, and would really appreciate some help.

Thanks :)

A. Price
  • 23
  • 1
  • 1
  • 5

1 Answers1

0

You may rearrange your exception handling to use this properly.

try
{
    //trying something
}
catch(SomeException e)
{
    //we failed
    e.printStackTrace();
}
finally
{
    //called when we failed or when we succeeded, even after a return; statement
}

EDIT

This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.

try {
    FileReader file_to_read = new FileReader(path);
    BufferedReader br1 = new BufferedReader(file_to_read);

    ArrayList<String> linesRead = new ArrayList<String>();

    String line = br1.readLine();

    while(line != null)
    {
        linesRead.add(line);
        line = br1.readLine();
    }

    br1.close();

for (int row=0; row < lineNumber; row++) {         
    try {
    //Reads the set and the subject in the text file
    String strSetSubjectLine = linesRead.get(row);
Luftbaum
  • 303
  • 1
  • 13
  • I get it, and its a good idea, I am just not sure where I would put it in my code. There is only 1 try/catch outside the for loop, and if I put it there, my buffered readers inside don't work, but if I put it inside the for loop, I get a stream closed error. Thanks for the idea though. – A. Price Jul 06 '17 at 09:10
  • I don't get your problem. Normally you close a reader, when you don't need it anymore. So just do it that way. – Luftbaum Jul 06 '17 at 09:12
  • I just don't know where to close it in my code. If I close it inside my for loop I get a stream closed error. If I close it after my for loop, my other buffered readers won't work because the first buffered reader is still open. Its a stupid problem, I know, but I just don't know what I've done wrong. Thanks for trying!! – A. Price Jul 06 '17 at 09:13
  • How about a previous reading block, where you read everything out of the file with the br1 reader and store it in a local ArrayList. Afterwards you close the reader and use the list for the for loop. – Luftbaum Jul 06 '17 at 09:17