Problema Inserir Dados No Arquivo .txt AJUDA!

3 respostas
M

Olá pessoal, estou com um trabalho de faculdade pra entregar.

O problema é o seguinte: eu consigo inserir no arquivo .txt até o segundo objeto da classe Pizza, quando eu vou inserir ele dá a seguinte exceção: NoSuchElementException

estou enviando-lhes o código para vocês darem uma olhada

CLASSE ArquivoPizza

package Modelo;

import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.io.File;

public class ArquivoPizza {
	
	private Formatter saida;
	private Scanner entrada;
	private ArrayList<Pizza> listaPizza;
	private static final String NOMEARQUIVO = "pizzas.txt";
	
	public void abreArquivo() {		
		try {
			entrada = new Scanner(new File(NOMEARQUIVO)); //
			lerDados(entrada);
		}
		catch (FileNotFoundException filesNotFoundException) {
			System.err.println("Arquivo vazio...");
			criarArquivo();
		}		
	}
	
	public void criarArquivo() {
		try {
			saida = new Formatter(NOMEARQUIVO);
                     
		}
		catch (SecurityException securityException) {
			System.err.println("Voc� n�o tem acesso a escrita nesse arquivo!");
			System.exit(1);
		}
		catch (FileNotFoundException fileNotFoundException) {
			System.err.println("Erro na cria��o do arquivo!");
			System.exit(1);
		}		
	}
	
	public void fecharArquivo() {
		if(entrada != null)
			entrada.close();
		if(saida != null)
			saida.close();
	}
	
	public void lerDados(Scanner entrada) {
                
                    listaPizza = new ArrayList<Pizza>();
                
		try {
			while(entrada.hasNext()){
				Pizza p = new Pizza();
				p.setSabor(entrada.nextLine());
				p.setPreco(entrada.nextDouble());
                                listaPizza.add(p);
			}
		}
		catch (NoSuchElementException noSuchElementException) {
			System.err.println("Arquivo Formatado de maneira inapropriada!");
			entrada.close();
			System.exit(1);
		}
		catch (IllegalStateException illegalStateException) {
			System.err.println("Erro de leitura do arquivo!");
			System.exit(1);
		}
	}
	
	public void cadastrarPizza(Pizza p) {
		listaPizza.add(p);
		salvarPizzas();
		fecharArquivo();
	}
	
	public void salvarPizzas() {
		criarArquivo();
		for(Pizza p : listaPizza) {
			saida.format("%s\n%.2f\n", p.getSabor(), p.getPreco());
		}
	}
}

CLASSE Principal (classe com o main)

package Controle;

import Modelo.*;
import GUI.AbaPainel;
import javax.swing.JFrame;

public class Principal {

    public static void main(String[] args) {

        Pizza x = new Pizza(30.0, "Carne");
        ArquivoPizza arqPizza = new ArquivoPizza();
        arqPizza.abreArquivo();
        arqPizza.abreArquivo();
        arqPizza.cadastrarPizza(x);


        Pizza y = new Pizza(20.0, "Escarola");
        arqPizza.abreArquivo();
        arqPizza.cadastrarPizza(y);

        Pizza k = new Pizza(10.0, "Atum");
        arqPizza.abreArquivo();
        arqPizza.cadastrarPizza(k);

        Pizza j = new Pizza(10.0, "Mussarela");
        arqPizza.abreArquivo();
        arqPizza.cadastrarPizza(j);
    }
}

3 Respostas

marcelohd02

Melhor Forma de escrever em arquivos.txt em java é usando

http://www.guj.com.br/article.show.logic?id=13

ou assim

// Este exemplo mostra como escrever em um arquivo

import java.io.*;

public class Estudos{
  public static void main(String[] args){
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter("conteudo.txt"));
        out.write("Esta é a primeira linha de texto
"); // "
" = quebra de linha no Windows 
        out.write("Esta é a segunda linha de texto");
        out.close();
    }
    catch(IOException e){
        // possiveis erros são tratados aqui
    }

    System.out.println("Acabei de escrever no arquivo");
    
    System.exit(0);
  }
}
M

ótimo consegui, valeu aii

e como seria para eu pegar os dados de conteudo.txt e exibir na tela?

renamed

Ola mateus

eu escrevi sobre isso num post ha poucos dias, acho que tem sua solução la

http://www.guj.com.br/posts/list/144929.java#781122

ok? :smiley:

Criado 23 de novembro de 2009
Ultima resposta 24 de nov. de 2009
Respostas 3
Participantes 3