File reading in IDE works and at the time it generates .jar does not work

2

I have an application that reads a text file that is in the same folder as the application. When I run the program on netbeans it reads the normal file:

ButwhenIgeneratetheJARitdoesnotreadthefile:

I'vecheckedifwhentheJARisgeneratedthetextfileisinthepackageanditis.Cananyonehelpme??

Testprogramcode:

packageNewClass;importjava.io.BufferedReader;importjava.io.FileReader;importjava.io.IOException;importjava.net.URL;publicclassNewJFrameextendsjavax.swing.JFrame{publicNewJFrame(){initComponents();URLurl2=this.getClass().getResource("teste.txt");//RECEBE A URL DO CAMINHO DO ARQUIVO 'Caminhopadrao'
    String path = url2.toString().replace("file:", "");//TRANSFORMA A URL EM STRING E MUDA O TRECHO 'file:' PARA NADA
    try {
        BufferedReader buffRead = new BufferedReader(new FileReader(path));//INSTANCIA UM BUFFER PARA LER O ARQUIVO
        String linha = "";//INICIALIZA A VARIÁVEL QUE RECEBERÁ O QUE LER DO ARQUIVO
        linha = buffRead.readLine();//GRAVA NA VARIAVÉL A LEITURA DO ARQUIVO
        jLabel1.setText(linha);//INSERE NO CAMPO DE TEXTO CDO CAMINHO A LEITURA DO ARQUIVO                
        buffRead.close();//ENCERRA O BUFFER DE LEITURA
    } catch (IOException e2) {
    }
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    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, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

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

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    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 ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration                   
}
    
asked by anonymous 14.05.2018 / 02:04

1 answer

4

The problem is that within the jar the text file is no longer considered a physical file system file, and the methods it is using only have a URL based on this system.

When you run the project via IDE, what actually happens is the execution of the project by the local file system, it does not create a jar to execute it, it just loads the bytecodes already compiled from some operating system folder, so your code works when executed directly from it, but when it generates the jar, it can not read the file.

To access the file correctly, use the getResourceAsStream() " and to load it itself, use a InputStreamReader ":

try {
    BufferedReader buffRead = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("teste.txt")));//INSTANCIA UM BUFFER PARA LER O ARQUIVO
    String linha = "";//INICIALIZA A VARIÁVEL QUE RECEBERÁ O QUE LER DO ARQUIVO
    linha = buffRead.readLine();//GRAVA NA VARIAVÉL A LEITURA DO ARQUIVO
    jLabel1.setText(linha);//INSERE NO CAMPO DE TEXTO CDO CAMINHO A LEITURA DO ARQUIVO                
    buffRead.close();//ENCERRA O BUFFER DE LEITURA
} catch (IOException e2) {
}

Tip: If you do not handle exception, do not use empty catch.

    
14.05.2018 / 02:22