Identificar o quanto de um arquivo já foi lido

Eu tô tentanando fazer um método que carrega um JProgressBar enquanto um arquivo é carregado da seguinte forma:

public void setProgressBar(File f) throws FileNotFoundException, IOException{
       Progress prog = new Progress();

       long tam= 0;
       long setNum;
       int i;
       arquive = new RandomAccessFile(f, "r");

       while(tam != f.length()){
           i = (int)tam;
           
           prog.setValue(i);
           try {
                Thread.sleep(25);
            }//end try
                catch (InterruptedException ie){
                System.err.println(ie);
            }//end catch
           tam = 100* arquive.getFilePointer()/f.length();
           
       }


    }

Porém não está funcionando, e o q eu percebi é q o arquive.getFilePointer() sempre está com o valor 0.
Será q alguém poderia me ajudar?
Obrigada

No seu código você está lendo o arquivo? Não vi nenhum “read” nesse código

na verdade eu tô lendo apartir desse código q está em outra classe:

public  byte[] readMap(RandomAccessFile fis,int width, int height) throws IOException{
         byte mapArea[] = new byte[width*height];
         fis.read(mapArea);
         return mapArea;
      }

[quote] public byte[] readMap(RandomAccessFile fis,int width, int height) throws IOException{ byte mapArea[] = new byte[width*height]; fis.read(mapArea); return mapArea; } [code] public void setProgressBar(File f) throws FileNotFoundException, IOException{
Progress prog = new Progress();

   long tam= 0;  
   long setNum;  
   int i;  
   arquive = new RandomAccessFile(f, "r"); [/code][/quote]

fis e f são o mesmo objeto?

então dei uma mudada no código:

public  byte[] readMap(RandomAccessFile fis,int width, int height) throws IOException{
         byte mapArea[] = new byte[width*height];
         fis.read(mapArea);
          Progress prog = new Progress();
       long tam= 0;
      
       int i;


       while(tam < 100){
           i = (int)tam;

           prog.setValue(i);
           try {
                Thread.sleep(25);
            }//end try
                catch (InterruptedException ie){
                System.err.println(ie);
            }//end catch

           tam = 100* fis.getFilePointer()/fis.length();
       }
         return mapArea;
      }

Acho q faz mais sentido… mas mesmo assim não funcionou

O read não deveria ser dado dentro do loop?

Coloquei assim e tb não funcionou:


while(tam < 100){
           fis.read(mapArea);
           i = (int)tam;
           prog.setValue(i);
           try {
                Thread.sleep(5);
            }//end try
                catch (InterruptedException ie){
                System.err.println(ie);
            }//end catch

           tam = 100* fis.getFilePointer()/fis.length();
           System.out.println(fis.getFilePointer());
       }
         return mapArea;
      }

Ah, agora entendi o que você quer fazer.
Você leu tudo de uma vez com um comando só ( fis.read(mapArea); ).
Só que esse comando leva um certo tempo para ser executado, se mapArea for realmente grande. O problema é que você quer pôr um JProgressBar para ir mostrando o progresso “em paralelo” com a leitura.
Para poder usar um JProgressBar, no seu caso, você pode tentar uma de duas coisas:

a) Crie o JProgressBar como “indeterminate”, então chame o comando para ler o arquivo, e a seguir, depois de lido o arquivo, desligue o JProgressBar;
ou então
b) Crie o JProgressBar normalmente, leia o arquivo em pedacinhos (não todo ele de uma vez), e nesse caso é que você pode ir atualizando o valor do JProgressBar.

vc poderia dar um exemplo do primeiro caso? Ficaria muito agradecida caso pudesse. Obrigada!

Não tenho muita experiência em java desktop, mas imagino que o progressbar indeterminate é aquele que fica de um lado pro outro, ou dando voltas, e não mostra exatamente o progresso de leitura do arquivo…

Acho que deve haver algum jeito de colocar o progressbar em uma thread separada e fazer as duas coisas juntas, só não sei como (ainda) vou pesquisar… :stuck_out_tongue:

sim indeterminate ele fica dando voltas… o problema eh q como eu vou saber quando o processo de leitura jah foi terminado se ele lê tudo de uma vez só???

Posso estar falando besteira mas parece que vc poderia resolver esse problema usando threads.

eu fiz do seguinte jeito:

public class Metodos implements Runnable  {

  public Metodos(File f) throws FileNotFoundException, IOException{
            new Thread(this).start();
            readMap(fis, mapWidth, mapHeight);
  }

 public  byte[] readMap(RandomAccessFile fis,int width, int height) throws IOException{
         byte mapArea[] = new byte[width*height];
         fis.read(mapArea);
         
         return mapArea;
      }

  public void run() {
        Progress p = new Progress();
        if(fim){
            p.disposeIt();
        }
    }

Mas o q tah acontecendo é que o ProgressBar soh aparece depois q o prcesso de leitura eh finalizado, mesmo eu colocando a thread para ser iniciada antes disso…

Exemplo dos dois casos.

package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class IndeterminateProgressBarExample extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JProgressBar prbLeituraArquivoGrande = null;
    private JPanel pnlBotoes = null;
    private JButton btnIndeterminate = null;
    private JButton btnStandard = null;

    /**
     * This method initializes prbLeituraArquivoGrande
     * 
     * @return javax.swing.JProgressBar
     */
    private JProgressBar getPrbLeituraArquivoGrande() {
        if (prbLeituraArquivoGrande == null) {
            prbLeituraArquivoGrande = new JProgressBar();
        }
        return prbLeituraArquivoGrande;
    }

    /**
     * This method initializes pnlBotoes
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getPnlBotoes() {
        if (pnlBotoes == null) {
            pnlBotoes = new JPanel();
            pnlBotoes.setLayout(new FlowLayout());
            pnlBotoes.add(getBtnIndeterminate(), null);
            pnlBotoes.add(getBtnStandard(), null);
        }
        return pnlBotoes;
    }

    /**
     * This method initializes btnIndeterminate
     * 
     * @return javax.swing.JButton
     */
    private JButton getBtnIndeterminate() {
        if (btnIndeterminate == null) {
            btnIndeterminate = new JButton();
            btnIndeterminate.setText("Indeterminate");
            btnIndeterminate.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    new Thread(new Runnable() {
                        public void run() {
                            btnIndeterminate.setEnabled(false);
                            prbLeituraArquivoGrande.setIndeterminate(true);
                            try {
                                Thread.sleep(5000); // simula um processo lento
                            } catch (InterruptedException ex) {
                            }
                            prbLeituraArquivoGrande.setIndeterminate(false);
                            btnIndeterminate.setEnabled(true);
                        }
                    }).start();
                }
            });
        }
        return btnIndeterminate;
    }

    /**
     * This method initializes btnStandard
     * 
     * @return javax.swing.JButton
     */
    private JButton getBtnStandard() {
        if (btnStandard == null) {
            btnStandard = new JButton();
            btnStandard.setText("Standard");
            btnStandard.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    new Thread(new Runnable() {
                        public void run() {
                            btnStandard.setEnabled(false);
                            prbLeituraArquivoGrande.setValue(0);
                            for (int i = 0; i < 100; ++i) {
                                try {
                                    prbLeituraArquivoGrande.setValue(i);
                                    Thread.sleep(50); // simula um processo lento
                                    // mas que foi dividido em partes
                                } catch (InterruptedException ex) {
                                }
                            }
                            prbLeituraArquivoGrande.setValue(100);
                            btnStandard.setEnabled(true);
                        }
                    }).start();

                }
            });
        }
        return btnStandard;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                IndeterminateProgressBarExample thisClass = new IndeterminateProgressBarExample();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * This is the default constructor
     */
    public IndeterminateProgressBarExample() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("Exemplo de JProgressBar");
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getPrbLeituraArquivoGrande(), BorderLayout.NORTH);
            jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }

}

o problema continua sendo q o a barra soh aparece completamente qdo o processo de leitura eh realizado…

Então eu testei seu exemplo… mas quando eu coloco as duas janelas ( uma q está com o JProgressBar e a outra q tem a imagem q estou lendo byte a byte), acontece q a q estah com a barra de progresso o aparece, porém não completamente…é como se o meu micro estivesse travando…ela soh passa a ficar totalmente visivel quando todo o processo de leitura da figura eh completado… mesmo eu colocando a thread do Frame q contém o JProgressBar antes de eu chamar o processo de leitura… O q me parece é q um ainda depende do outro mesmo com o uso da thread
:frowning:

Tenta fazer o seguinte:

byte[] b = new byte[2048];
int length;

		while ((length = is.read(b)) != -1) {
			for (int i = 1; i < length; i++)
				Barra.tamanho.add(i);

			System.out.println();
			arquivo.write(b, 0, length);
		}

Onde is é o InputStream e o arquivo é o Arquivo a ser gravado.

Desculpa, mas eu não entendi dias coisas:

  1. eu não entendi o q seria esse comando:
Barra.tamanho.add(i); //Barra é o meu JProgressBar? Tamanho seria o length?
  1. eu não quero gravar nada, apenas ler…

Acho q eu não entendi o seu exemplo…
Vc poderia explicar???
Obrigada!!!