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

Asked

Viewed 343 times

2

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

inserir a descrição da imagem aqui

But when I Gero the JAR it does not read the file:

inserir a descrição da imagem aqui

I have already checked if when JAR is generated the text file is in the package and is. Can anyone help me??

Code of the test program:

package NewClass;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
    initComponents();
    URL url2 = 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                   
}
  • The file is inside the jar or outside?

  • The file is inside the jar

  • How is the structure of your project?

  • What do you mean the structure?? You say the folder structure??

1 answer

3


The problem is that within the jar the text file is no longer considered a physical file from the file system, and the methods you are using only bring 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 filesystem, it(IDE) does not create a jar to run 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 cannot read the file.

To access the file correctly, use the method getResourceAsStream() and to load it properly, 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 not treat exception, do not use empty catch.

  • Thanks for the attention and the solution, it worked.

  • @Pedroafonso in the title you say compiler, but didn’t mean IDE? Because the compiler has nothing to do with the problem.

  • Yeah, sorry for the inattention.

  • How do I write to the file, I was using the same method by the url, which classes I should use to write to the file with this method you showed?

  • @Pedroafonso can’t, the file inside jar is read-only.

  • I get it, thank you

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.