olha eu estou tentando em colocar em pra tica meus estudos
e nfim um programinha ainda em faze de testes
ele tem um escritor um garavador que grava o arquivo uma classe que abre ou cria o arquivo, um banco para a GUI , um gravador (para controles de tamanho essas coisas), e um leitorpara fazer um estilo relastório.
bem vou mostrar as classes para vcs e queria saber pq o que quando eu modifico os dados com a classe aceso e gravação e executo meu relatório
os meus dados aparecem coisas estrtanhas ???
deem uma olhadinha na imagem e no no cod pra ve se vcs podem me dizer ond eu estou errando
// Banco GUI hehe
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class BancoUI extends JPanel{
// texto de rótulos para a GUI
protected final static String names[] = { "Numero do Produto", "Produto", "Quantidade", "Soma do Produto", "Subtrai do Produto", "valor do Produto", "total em estoque", "total vendido", "preço de compra", "Total de compras" };
// componentes GUI; protected para acesso por futuras subclasses
protected JLabel labels[];
protected JTextField fields[];
protected JButton doTask1, doTask2, doTask3, doTask4;
protected JPanel innerPanelCenter, innerPanelSouth;
// número de campos de texto na GUI
protected int size;
public static final int NUMERODOPRODUTO = 0, PRODUTO = 1, QUANTIDADE = 2, SOMAPRODUTO = 3, SUBTRAIPRODUTO = 4, VALORDOPRODUTO = 5, TOTALEMESTOQUE = 6, TOTALVENDIDO = 7, PREÇODECOMPRA = 8, TOTALDECOMPRAS = 9;
/* configura a GUI. Argumento 4 para o construtor cria quatro linhas
* de componentes GUI. Argumento 5 para o construtor ( usado em outro programa, adiante ) cria cinco linhas de componentes GUI
*/
/** Creates a new instance of BancoUI */
public BancoUI(int mySize ) {
size = mySize;
labels = new JLabel[ size ];
fields = new JTextField[ size ];
// cria rótulos
for ( int count = 0; count < labels.length; count++ )
labels[ count ] = new JLabel( names[ count ] );
// cria campos de texto
for ( int count = 0; count < fields.length; count++)
fields[ count ] = new JTextField();
// cria painel para dispor os rótulos e os campos de texto
innerPanelCenter = new JPanel();
innerPanelCenter.setLayout( new GridLayout( size, 2 ) );
// anexa rótulos e campos de texto a innerPanelCenter
for ( int count = 0; count < size; count++ ){
innerPanelCenter.add( labels[ count] );
innerPanelCenter.add( fields[ count ] );
}
doTask1 = new JButton();
doTask2 = new JButton();
doTask3 = new JButton();
doTask4 = new JButton();
// cria painel para dispor os botões e anexa os botõe
innerPanelSouth = new JPanel();
innerPanelSouth.add( doTask1 );
innerPanelSouth.add( doTask2 );
// configura Layout deste conatiner e anexa painels a ele
setLayout( new BorderLayout() );
add( innerPanelCenter, BorderLayout.CENTER );
add( innerPanelSouth, BorderLayout.SOUTH );
// valida o layout
validate();
} // fim do construtor
// devolve referência para o botão genérico de tarefas do Task1
public JButton getDoTask1Button() {
return doTask1;
}
public JButton getDoTask2Button(){
return doTask2;
}
public JButton getDoTask3Button() {
return doTask3;
}
public JButton getDoTask4Button() {
return doTask4;
}
// devolve referência para um array de JTextField
public JTextField[] getFields() {
return fields;
}
// Limpa p conteudo dos campos de texto
public void clearFields() {
for ( int count = 0; count < size; count++ )
fields[ count ].setText( "" );
}
// configura valores dos campos de texto dispara IllegalArgumentException se o argumento contiver um número incorreto de Strings
public void setFieldValues( String strings[] ) throws IllegalArgumentException {
if ( strings.length != size )
throw new IllegalArgumentException( "There must be " + size + " Strings in the array" );
for ( int count = 0; count < size; count++ )
fields[ count ].setText( strings[ count ] );
}
// obtem array de string com o conteudo atual dos conteudos dos campos de texto
public String[] getFieldValues() {
String values[] = new String[ size ];
for ( int count = 0; count < size; count++ )
values[ count ] = fields[ count ].getText();
return values;
}
} // fim da classe BancoUI
// Acesso e gravação
import java.io.RandomAccessFile;
import java.io.IOException;
import kastiberg.GravaConta;
public class AcessoEGravação extends GravaConta {
// valor defalt para Acesso e gravação
public AcessoEGravação()
{
this ( 0, "", 0, 0, 0, 0.0, 0, 0.0, 0.0, 0.0 );
}
// inicializa Acesso e Gravação
public AcessoEGravação( int numeroDoProduto,
String produto,
int quantidade,
int somaProduto,
int subtraiProduto,
double valorProduto,
int totalEmEstoque,
double totalVendido,
double preçoDeCompra,
double totalDeCompra ) {
super(
numeroDoProduto,
produto,
quantidade,
somaProduto,
subtraiProduto,
valorProduto,
totalEmEstoque,
totalVendido,
preçoDeCompra,
totalDeCompra );
}
// ler a gravação e especifica ao arqquivo recebido RandomAccessFile
public void read( RandomAccessFile file ) throws IOException
{
setNumeroProduto( file.readInt() );
setProduto( readName( file ) );
setQuantidade( file.readInt() );
setSomaProduto( file.readInt() );
setSubtraiProduto( file.readInt() );
setValorProduto( file.readDouble() );
setTotalEmEstoque( file.readInt() );
setTotalVendido( file.readDouble() );
setPreçoDeCompra( file.readDouble() );
setTotalCompra( file.readDouble() );
} // fim do metodo read
// limita o tamanho dos String
private String readName( RandomAccessFile file ) throws IOException
{
char name[] = new char[ 18 ], temp;
for ( int count = 0; count < name.length; count++ )
{
temp = file.readChar();
name[ count ] = temp;
} // end for
return new String( name ).replace( '[code]
// Acesso e gravação
import java.io.RandomAccessFile;
import java.io.IOException;
import kastiberg.GravaConta;
public class AcessoEGravação extends GravaConta {
// valor defalt para Acesso e gravação
public AcessoEGravação()
{
this ( 0, "", 0, 0, 0, 0.0, 0, 0.0, 0.0, 0.0 );
}
// inicializa Acesso e Gravação
public AcessoEGravação( int numeroDoProduto,
String produto,
int quantidade,
int somaProduto,
int subtraiProduto,
double valorProduto,
int totalEmEstoque,
double totalVendido,
double preçoDeCompra,
double totalDeCompra ) {
super(
numeroDoProduto,
produto,
quantidade,
somaProduto,
subtraiProduto,
valorProduto,
totalEmEstoque,
totalVendido,
preçoDeCompra,
totalDeCompra );
}
// ler a gravação e especifica ao arqquivo recebido RandomAccessFile
public void read( RandomAccessFile file ) throws IOException
{
setNumeroProduto( file.readInt() );
setProduto( readName( file ) );
setQuantidade( file.readInt() );
setSomaProduto( file.readInt() );
setSubtraiProduto( file.readInt() );
setValorProduto( file.readDouble() );
setTotalEmEstoque( file.readInt() );
setTotalVendido( file.readDouble() );
setPreçoDeCompra( file.readDouble() );
setTotalCompra( file.readDouble() );
} // fim do metodo read
// limita o tamanho dos String
private String readName( RandomAccessFile file ) throws IOException
{
char name[] = new char[ 18 ], temp;
for ( int count = 0; count < name.length; count++ )
{
temp = file.readChar();
name[ count ] = temp;
} // end for
return new String( name ).replace( '\0', ' ' );
} // end method readName
// grava umm registro
public void write( RandomAccessFile file ) throws IOException
{
file.writeInt( getNumeroProduto() );
writeName( file, getProduto() );
file.writeInt( getQuantidade() );
file.writeInt( getSomaProduto() );
file.writeInt( getSubtraiProduto() );
file.writeDouble( getValorProduto() );
file.writeInt( getTotalEmEstoque() );
file.writeDouble( getTotalVendido() );
file.writeDouble( getTotalCompra() );
file.writeDouble( getTotalCompra() );
} // end method write
// write a name to file; maximum of 15 characters
private void writeName( RandomAccessFile file, String name )
throws IOException
{
StringBuffer buffer = null;
if ( name != null )
buffer = new StringBuffer( name );
else
buffer = new StringBuffer( 15 );
buffer.setLength( 15 );
file.writeChars( buffer.toString() );
} // end method writeName
public static int size() {
return 72;
}
} // acabou !
// grava umm registro
public void write( RandomAccessFile file ) throws IOException
{
file.writeInt( getNumeroProduto() );
writeName( file, getProduto() );
file.writeInt( getQuantidade() );
file.writeInt( getSomaProduto() );
file.writeInt( getSubtraiProduto() );
file.writeDouble( getValorProduto() );
file.writeInt( getTotalEmEstoque() );
file.writeDouble( getTotalVendido() );
file.writeDouble( getTotalCompra() );
file.writeDouble( getTotalCompra() );
} // end method write
// write a name to file; maximum of 15 characters
private void writeName( RandomAccessFile file, String name )
throws IOException
{
StringBuffer buffer = null;
if ( name != null )
buffer = new StringBuffer( name );
else
buffer = new StringBuffer( 15 );
buffer.setLength( 15 );
file.writeChars( buffer.toString() );
} // end method writeName
public static int size() {
return 72;
}
} // acabou ![/code]
//Criar e acessar java
// quando eu crio um arquivo com essa classe meu leitor consegue ler
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.swing.JFileChooser;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class CriarEAcessar extends JFrame
{
private static final int NUMBER_RECORDS = 100;
// Aria abre arquivo
public void CriarArquivo()
{
// exibe dialogo para que o usuário possa esclher o local
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showSaveDialog( null );
if (result == JFileChooser.CANCEL_OPTION )
return;
File nomeDoArquivo = fileChooser.getSelectedFile();
if ( nomeDoArquivo == null || nomeDoArquivo.getName().equals( "" ) )
JOptionPane.showMessageDialog( null, "Nome de Arquivo Invalido", "Nome de arquivo invalido", JOptionPane.ERROR_MESSAGE );
else {
try // abre try
{
RandomAccessFile arquivo = new RandomAccessFile( nomeDoArquivo, "rw" );
AcessoEGravação record = new AcessoEGravação();
// write 100 blank records
for ( int count = 0 ; count < NUMBER_RECORDS; count++ )
record.write( arquivo );
// display message that file was created
arquivo.close();
JOptionPane.showMessageDialog( null, "Arquivo criado com sucesso...", "Criação completa", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate program
} // end try
catch ( IOException ioException )
{
JOptionPane.showMessageDialog( null, "Erro de Acesso ao Arquivo", "Erro", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end catch
} // end method createFile
// fecha arquivo ao clicar no botão fechar
addWindowListener(
// classe interna anônima para o ouvinte windowListener
new WindowAdapter() {
// comando que fecha janela
public void windowClosing( WindowEvent event ){
System.exit( 0 );
}
} // fim da classe anônima Interna
); // fim da chamada para addActionListener
}
public static void main( String args[] )
{
CriarEAcessar application = new CriarEAcessar();
application.CriarArquivo();
} // end main
} // end class CreateRandomFile
// escritor.java escreve arquivos no meu programa
// quando eu tento colocar os dados eu não consigo ler
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import kastiberg.*;
import javax.swing.JFrame;
public class Escritor extends JFrame
{
private RandomAccessFile output;
private BancoUI userInterface;
private JButton enterButton, openButton;
private static final int NUMBER_RECORDS = 100;
public Escritor() {
super( "Guardador de Arquivo" );
// cria instância da interface reutilizavel com o BancoUI
userInterface = new BancoUI( 10 ); // dez campos de texto // quatro campos de texto
getContentPane().add( userInterface, BorderLayout.CENTER );
// obtem referência para o botão de tarefa generico
openButton = userInterface.getDoTask1Button();
openButton.setText( "Abrir..." );
openButton.addActionListener(
// classe interna anônima para tratar eventos de openButton
new ActionListener() {
public void actionPerformed( ActionEvent event ) {
openFile();
}
} // fim da classe interna Anônima
); // fim da chamada para AddActionListener
// obtém referência para o botão de tarefa genérico doTaskButton1
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Save" );
enterButton.setEnabled( false );
// registra ouvinte para chamar addRecord quando o botão é pressionado
enterButton.addActionListener(
// registra ouvinte para chamar addRecord quando o botão é pressionado
new ActionListener() {
// adiciona registro ao arquivo
public void actionPerformed( ActionEvent event ){
addRecords();
}
} // fim da classe interna anônima
); // fim da chamada de AddActionListener
// fecha arquivo ao clicar no botão fechar
addWindowListener(
// classe interna anônima para o ouvinte windowListener
new WindowAdapter() {
// comando que fecha janela
public void windowClosing( WindowEvent event ){
closeFile();
System.exit( 0 );
}
} // fim da classe anônima Interna
); // fim da chamada para addActionListener
setSize( 400, 350 );
show();
}
// abre o arquivo
public void openFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// se o usuario clicou no botão Cancel no dialog, retona
if ( result == JFileChooser.CANCEL_OPTION )
return;
// Obtem arquivo selecionado
File nomeDoArquivo = fileChooser.getSelectedFile();
// exibe erro se o nome do arquivo for invalido
if ( nomeDoArquivo == null || nomeDoArquivo.getName().equals( "" ) )
JOptionPane.showMessageDialog( this, "Nome ou tipo de arquivo invalido", "Erro de Nome", JOptionPane.ERROR_MESSAGE );
else {
try
{
output = new RandomAccessFile( nomeDoArquivo, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
} // end try
// processa exe~ção ocorrida enquanto estava abrindo o arquivo
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Arquivo não Existe", "Nome de Arquivo invalido", JOptionPane.ERROR_MESSAGE );
}// end catch
} // fim do Else
}// end method openFile
// fecha o arquivo e termina o aplicativo
public void closeFile()
{
try
{
if ( output != null )
output.close();
} // end try
catch ( IOException ioException )
{
JOptionPane.showMessageDialog( this, "Erro closing file", "Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // finaliza catch
} // finaliza o closeFile
// add records to file
public void addRecords()
{
AcessoEGravação record = new AcessoEGravação();
int numeroDoProduto = 0;
String fields[] = userInterface.getFieldValues();
// assegura que o campo de conta tem um valor
if ( ! fields[ BancoUI.NUMERODOPRODUTO ].equals( "" ) ) {
// envia valores para a saida no arquivo
try // output values to file
{
numeroDoProduto = Integer.parseInt( fields[ BancoUI.NUMERODOPRODUTO ] );
if ( numeroDoProduto > 0 && numeroDoProduto <= 100 ){
record.setNumeroProduto( numeroDoProduto );
record.setProduto( fields[ BancoUI.PRODUTO ] );
record.setQuantidade( Integer.parseInt( fields[ BancoUI.QUANTIDADE ] ) );
record.setSomaProduto( Integer.parseInt( fields[ BancoUI.SOMAPRODUTO ] ) );
record.setSubtraiProduto( Integer.parseInt( fields[ BancoUI.SUBTRAIPRODUTO ] ) );
record.setValorProduto(Double.parseDouble( fields[ BancoUI.VALORDOPRODUTO ] ) );
record.setTotalEmEstoque( Integer.parseInt( fields[ BancoUI.TOTALEMESTOQUE ] ) );
record.setTotalVendido( Double.parseDouble( fields[ BancoUI.TOTALVENDIDO ] ) );
record.setPreçoDeCompra( Double.parseDouble( fields[ BancoUI.PREÇODECOMPRA ] ) );
record.setTotalCompra( Double.parseDouble( fields[ BancoUI.TOTALDECOMPRAS ] ) );
output.seek( ( numeroDoProduto - 1 ) * AcessoEGravação.size() ); // location for file
record.write( output );
//
} // finaliza o if
userInterface.clearFields(); // Lismpa os textFields
} // finaliza o if try
catch( NumberFormatException formatException ){
JOptionPane.showMessageDialog(this, "Desculpe essa verção é de apenas demostração " +
"\nsuporta apenas contas de 0 a 100", "adiquira a verção completa", JOptionPane.INFORMATION_MESSAGE );
return;
}
catch ( IOException ioException )
{
JOptionPane.showMessageDialog(this, "Numero Inválido", "Erro", JOptionPane.ERROR_MESSAGE );
closeFile();
} // end catch
catch ( NoSuchElementException elementException )
{
JOptionPane.showMessageDialog( this, "Entrada Invalida", "Tente Novamente.", JOptionPane.ERROR_MESSAGE );
return;
} // termina o catch
} // finaliza addRecords
} // termina aqui o WriteRandomFile
// executa o aplicativo
public static void main( String args[] ) {
new Escritor();
}
}
agora meu leitor
// leitor.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.io.File;
public class Leitor extends JFrame{
private RandomAccessFile input;
private JTextArea DysplayArea;
private JButton openButton; // botão abrir
private JButton mostrarButton; // botão mostrar relatório
private JPanel painel; // cria painel
String outputText;
// comfigura a GUI
public Leitor() {
super ( "Relatório" );
Container container = getContentPane();
// configura o painel para os botões
painel = new JPanel();
// cria e configura o botão para abrir o arquivo
openButton = new JButton( "Abrir..." );
painel.add( openButton );
// registra o ouvinte para openButton
openButton.addActionListener(
// classe interna anônima para tratar de openButton
new ActionListener() {
// abre o arquivo para processamento
public void actionPerformed( ActionEvent event ){
openFile();
}
} // fim da classe anônima
); // fim da chamada de addActionListener
mostrarButton = new JButton( "Gerar Relatório" );
painel.add( mostrarButton );
mostrarButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event ){
outputText = event.getActionCommand();
readRecords();
}
}
);
// configura a area de exibição
DysplayArea = new JTextArea();
JScrollPane barraDeRolagem = new JScrollPane( DysplayArea );
container.add( barraDeRolagem, BorderLayout.CENTER );
container.add( painel, BorderLayout.SOUTH );
// fecha arquivo ao clicar no botão fechar
addWindowListener(
// classe interna anônima para o ouvinte windowListener
new WindowAdapter() {
// comando que fecha janela
public void windowClosing( WindowEvent event ){
closeFile();
System.exit( 0 );
}
} // fim da classe anônima Interna
); // fim da chamada para addActionListener
pack();
setSize( 700, 300 );
show();
} // fim da GUI
// Abre arquivo
public void openFile()
{
// abre a janela para a escolha de arquivo
JFileChooser fileChooser = new JFileChooser();
// seleciona o arquivo marcado
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
// aqui guarda a informação da captura do arquivo escolhido na janela
int result = fileChooser.showOpenDialog( this );
// se o usuário não escolher um arquivo na janela e clicar no botão cancel ( ainda não sei como traduzir)
// ele retorna para o inicio.
if ( result == JFileChooser.CANCEL_OPTION )
return;
File nomeDoArquivo = fileChooser.getSelectedFile(); // aqui abre o arquivo
// caso o usuário não escolha um arquivo e deixe de escolher
// um arquivo ou escolha um arquivo válido ele trata e manda para um exception a autura
if ( nomeDoArquivo == null || nomeDoArquivo.getName().equals( "" ) );
else {
try // abre o arquivo
{
input = new RandomAccessFile( nomeDoArquivo, "r" );
openButton.setEnabled( false );
mostrarButton.setEnabled( true );
} // aqui acaba try
catch ( IOException ioException )
{
JOptionPane.showMessageDialog( this, "Arquivo Não Existe.", "Arquivo invalido.", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // fim catch
} // fim do else
} // fim do métodoopenFile
// read and display records
public void readRecords()
{
AcessoEGravação record = new AcessoEGravação();
DecimalFormat twoDigits = new DecimalFormat( "0.00" ); // num sei porque eu o coloquei mais deveria funcionar
try // Lê registros
{
DysplayArea.setText( "Registro:\n" );
while ( true )
{
record.read( input );
// while ( record.getNumeroProduto() == 0 ); // exeriência mal sucedida
// display grava
DysplayArea.append( record.getNumeroProduto() +
"\t" + record.getProduto() +
"\t" + record.getQuantidade() +
"\t" + record.getSomaProduto() +
"\t" + record.getSubtraiProduto() +
"\t" + record.getValorProduto() +
"\t" + record.getTotalEmEstoque() +
"\t" + record.getTotalVendido() +
"\t" + record.getPreçoDeCompra() +
"\t" + record.getTotalCompra() + "\n");
} // acaba while
} // aqui acaba o try
catch ( EOFException eofException ) // close file
{
return; // end of file was reached
} // aqui acaba o catch
catch ( IOException ioException )
{
System.err.println( "Error reading file." );
System.exit( 1 );
} // aqui acaba catch
} // aqui acaba readRecords
// fechar e finalizar o programa
public void closeFile()
{
try // fecha o arqui e sai
{
if ( input != null )
input.close();
} // aqui acaba try
catch ( IOException ioException )
{
System.err.println( "Error closing file." );
System.exit( 1 );
} // aqui acaba catch
} // aqui acaba closeFile
// executa arquivo
public static void main( String args[] ){
new Leitor();
}
} // aqui acaba a classe ReadRandomFile
alguem pode me da uma dica ou me dizer onde eu estou errando ???