Buscar

Trabalho3

Esta é uma pré-visualização de arquivo. Entre para ver o arquivo original

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import javax.swing.JOptionPane;
public class Trabalho3 {
 public static final String FILE_NAME = "names.txt";
 protected static NameList getList() throws IOException {
 return new NameList(new FileSource(FILE_NAME));
 }
 
 protected static Menu getMenu(NameList list) {
 return new Menu(list);
 }
 
 public static void main(String args[]) {
 try {
 Menu menu = getMenu(getList());
 menu.doAction();
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null, 
 "Não foi possível criar o arquivo", 
 "Erro de escrita!", 
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
}
// Name list
class NameList {
 private DataSource source;
 public NameList(DataSource source) {
 this.source = source;
 }
 public void append(String name) throws IOException {
 source.append(name);
 }
 public void writeTo(String name, int index) throws IOException {
 String[] names = source.read();
 String[] out = new String[Math.max(index + 1, names.length)];
 for (int i = 0; i < out.length; ++i) {
 try {
 out[i] = names[i] != null ? names[i] : "";
 } catch (ArrayIndexOutOfBoundsException e) {
 out[i] = "";
 }
 }
 out[index] = name;
 source.write(out);
 }
 public String[] findAll() throws IOException {
 return source.read();
 }
 public int find(String name) throws IOException {
 return source.search(name);
 }
 public String find(int index) throws IOException {
 String[] names = source.read();
 try {
 return !names[index].equals("") ? names[index] : null;
 } catch (ArrayIndexOutOfBoundsException e) {
 return null;
 }
 }
}
// Data source
interface DataSource {
 public void append(String data) throws IOException;
 public void write(String[] data) throws IOException;
 public String[] read() throws IOException;
 public int search(String data) throws IOException;
}
class FileSource implements DataSource {
 private File file;
 public FileSource(String name) throws IOException {
 file = new File(name);
 file.createNewFile();
 }
 @Override
 public void append(String data) throws IOException {
 BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
 writer.write(data);
 writer.newLine();
 writer.close();
 }
 @Override
 public void write(String[] data) throws IOException {
 BufferedWriter writer = new BufferedWriter(new FileWriter(file));
 for (int i = 0; i < data.length; ++i) {
 writer.write(data[i]);
 writer.newLine();
 }
 writer.close();
 }
 @Override
 public String[] read() throws IOException {
 String[] data = new String[getNumberOfLines()];
 BufferedReader reader = new BufferedReader(new FileReader(file));
 String item;
 int i = 0;
 while ((item = reader.readLine()) != null) {
 data[i++] = item;
 }
 reader.close();
 return data;
 }
 protected int getNumberOfLines() throws IOException {
 LineNumberReader reader = new LineNumberReader(new FileReader(file));
 reader.skip(Long.MAX_VALUE);
 int lines = reader.getLineNumber();
 reader.close();
 return lines;
 }
 @Override
 public int search(String data) throws IOException {
 String[] items = read();
 for (int i = 0; i < items.length; ++i) {
 if (data.equalsIgnoreCase(items[i])) {
 return i;
 }
 }
 return -1;
 }
}
// Menu
interface MenuCommand {
 public String getLabel();
 
 public void execute();
}
class Menu {
 MenuCommand[] commands = new MenuCommandImpl[6];
 
 public Menu(NameList list) {
 commands[0] = new AskNameAndAppend(list);
 commands[1] = new AskIndexAndShowName(list);
 commands[2] = new AskNameAndShowIndex(list);
 commands[3] = new WriteToIndexTwo(list);
 commands[4] = new ListAll(list);
 commands[5] = new Exit();
 }
 
 public void doAction() {
 try {
 getCommand().execute();
 doAction();
 } catch (NullPointerException e) {
 doAction();
 }
 }
 
 protected MenuCommand getCommand() {
 try {
 int option = Integer.parseInt(
 JOptionPane.showInputDialog(null, this, "Selecione sua opção", JOptionPane.INFORMATION_MESSAGE)
 );
 
 return commands[--option];
 } catch (ArrayIndexOutOfBoundsException e) {
 JOptionPane.showMessageDialog(
 null, 
 "A operação escolhida é inválida, por favor escolha novamente!", 
 "Operação inválida", 
 JOptionPane.ERROR_MESSAGE
 );
 
 return getCommand();
 } catch (NumberFormatException e) {
 return commands[5];
 }
 }
 
 @Override
 public String toString() {
 String message = "";
 
 for (int i = 0; i < commands.length; ++i) {
 message += (i + 1) + ") " + commands[i].getLabel() + "\n";
 }
 
 return message + "\n";
 }
}
abstract class MenuCommandImpl implements MenuCommand {
 protected NameList list;
}
class AskNameAndAppend extends MenuCommandImpl {
 public AskNameAndAppend(NameList list) {
 this.list = list;
 }
 
 @Override
 public String getLabel() {
 return "Solicitar nome e escrever no arquivo";
 }
 
 @Override
 public void execute() {
 try {
 list.append(
 JOptionPane.showInputDialog("Digite o nome a ser adicionado")
 );
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null,
 "Não foi possível escrever no arquivo!",
 "Erro de escrita",
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
}
class AskIndexAndShowName extends MenuCommandImpl {
 public AskIndexAndShowName(NameList list) {
 this.list = list;
 }
 
 @Override
 public String getLabel() {
 return "Solicitar uma posição do arquivo e mostrar o nome dessa posição";
 }
 
 @Override
 public void execute() {
 try {
 int index = Integer.parseInt(JOptionPane.showInputDialog("Digite a posição no arquivo"));
 String name = list.find(index);
 
 JOptionPane.showMessageDialog(
 null, 
 name == null ? "Nenhum dado foi encontrado nesta posição."
 : "Na posição #" + index + " está o nome: " + name
 );
 } catch (NumberFormatException e) {
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null,
 "Não foi possível ler o arquivo!",
 "Erro de leitura",
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
}
class AskNameAndShowIndex extends MenuCommandImpl {
 public AskNameAndShowIndex(NameList list) {
 this.list = list;
 }
 
 @Override
 public String getLabel() {
 return "Solicitar um nome e informar qual a posição dentro do arquivo";
}
 
 @Override
 public void execute() {
 String name = JOptionPane.showInputDialog("Digite o nome");
 
 try {
 int index = list.find(name);
 
 JOptionPane.showMessageDialog(
 null, 
 index < 0 ? "Nome não cadastrado."
 : "O nome " + name + " está na posição: #" + index
 );
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null,
 "Não foi possível ler o arquivo!",
 "Erro de leitura",
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
}
class WriteToIndexTwo extends MenuCommandImpl {
 public WriteToIndexTwo(NameList list) {
 this.list = list;
 }
 
 @Override
 public String getLabel() {
 return "Solicitar um nome e inserir na terceira posição do arquivo";
 }
 
 @Override
 public void execute() {
 try {
 String name = JOptionPane.showInputDialog("Digite o nome");
 
 if (name != null) {
 list.writeTo(name, 2);
 }
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null,
 "Não foi possível escrever no arquivo!",
 "Erro de escrita",
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
}
class ListAll extends MenuCommandImpl {
 public ListAll(NameList list) {
 this.list = list;
 }
 
 @Override
 public String getLabel() {
 return "Mostre todas as posições e nomes em apenas uma mensagem";
 }
 
 @Override
 public void execute() {
 try {
 String[] names = list.findAll();
 
 JOptionPane.showMessageDialog(null, createMessage(names));
 } catch (IOException e) {
 JOptionPane.showMessageDialog(
 null,
 "Não foi possível ler o arquivo!",
 "Erro de leitura",
 JOptionPane.ERROR_MESSAGE
 );
 }
 }
 
 protected String createMessage(String[] names)
 {
 if (names.length == 0) {
 return "Nenhum nome cadastrado!";
 }
 
 String message = "Os nomes cadastrados são:\n\n";
 
 for (int i = 0; i < names.length; ++i) {
 message += "#" + i + " - " + names[i] + "\n";
 }
 
 return message;
 }
}
class Exit extends MenuCommandImpl {
 @Override
 public String getLabel() {
 return "Sair";
 }
 
 @Override
 public void execute() {
 System.exit(0);
 }
}

Teste o Premium para desbloquear

Aproveite todos os benefícios por 3 dias sem pagar! 😉
Já tem cadastro?

Outros materiais