Question :
I started working a little bit at a company that programs the MiFire cards and I’m in the experimental phase. Meanwhile the engineer told me to do a job.
First step:
I have to enter two numeric values and get the result of the sum;
Save in a sequential file the parcels and the result of the sum;
Each saved file line “f1” contains 3 information:
linha1<- p1, p2, soma
linha2<- p1, p2, soma
Second stage:
Read the saved file and show the parcels with element of a multiplication and get the result.
Record in a txt file “f2” the elements and the product in each line.
I’m trying to do but I just can not, could anyone help me?
int n1 = Integer.parseInt(txtN1.getText());
int n2 = Integer.parseInt(txtN2.getText());
int soma = n1 + n2;
//int mult = n1 * n2;
txtR.setText(Integer.toString(soma));
//txtRM.setText(Integer.toString(mult));
String linhat = "";
//Ler e gravar no primeiro arquivo
File arq = new File("arquivo.txt");
try{
arq.createNewFile();
FileReader ler = new FileReader(arq);
FileWriter fileWriter = new FileWriter(arq);
BufferedWriter escrever = new BufferedWriter(fileWriter);
linhat = Integer.toString(n1)+ ";";
escrever.write(linhat);
linhat = Integer.toString(n2)+";";
escrever.write(linhat);
linhat = Integer.toString(soma) ;
escrever.write(linhat);
PrintWriter gravarArq = new PrintWriter(arq);
gravarArq.print(linhat);
escrever.close();
fileWriter.close();
BufferedReader lerb = new BufferedReader(ler);
String linha = lerb.readLine();
while(linha !=null){
System.out.println(linha);
linha = lerb.readLine();
//ler o ficheiro
File file = new File("arquivo.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
// gravar o ficheiro "f2"
File file = new File("arquivo2.txt");
FileWriter fw = new FileWrite(file);
BufferedReader bw = new BufferedReader(fw);
String s ="",
bw.newLine;
bw.write(s);
bw.flush();
/* Scanner in = new Scanner(new FileReader("arquivo.txt"));
while(in.hasNextLine()){
String line = scanner.nexteLine();
System.out.println(line);
*/
}
}catch (IOException ex){
}
Answer :
I do not know if I understood your problem correctly. See if this solution meets:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
public class TxtHandler {
private Path pathSoma;
private Path pathMultiplicacao;
public TxtHandler(Path pathSoma, Path pathMultiplicacao) {
super();
this.pathSoma = pathSoma;
this.pathMultiplicacao = pathMultiplicacao;
}
public static void main(String args[]) throws IOException, URISyntaxException {
//Diretório que o arquivo será escrito
URI dir = TxtHandler.class.getResource(".").toURI();
//arquivo que será usado para colocar os valores somados
Path pathSoma = Paths.get(dir).resolve("arquivoSoma.txt");
//aquivo que será usado para colocar os valores multiplicados
Path pathMultiplicacao = Paths.get(dir).resolve("arquivoMultiplicacao.txt");
TxtHandler txtHandler = new TxtHandler(pathSoma, pathMultiplicacao);
// passa os dois valores que deseja somar e multiplicar. O método irá somar e salvar no arquivo
txtHandler.salvarESomar(3, 6);
// ler do arquivo salvo anteriormente, multiplica os valores e salva em outro arquivo
txtHandler.lerMultiplicarESalvar();
}
public void salvarESomar(int n1, int n2) throws IOException {
int soma = n1+n2;
//O StringJoiner serve para concatenar valores utilizador um delimitador específico
StringJoiner joiner = new StringJoiner(";");
joiner.add(String.valueOf(n1)).add(String.valueOf(n2)).add(String.valueOf(soma));
List <String> linhas = Arrays.asList(joiner.toString());
//Esse método recebe o caminho do arquivo, o conteúdo a ser escrito através de uma lista de strings e
//de que maneira o arquivo será manipulado. Nesse caso a opção CREATE signfica que se o arquivo não existir,
//ele será criado. A opção APPEND irá adicionar o conteúdo sempre no final do arquivo.
//
Files.write(pathSoma, linhas, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
private String getLinha(int n1, int n2, int result) {
StringJoiner joiner = new StringJoiner(";");
joiner.add(String.valueOf(n1)).add(String.valueOf(n2)).add(String.valueOf(result));
return joiner.toString();
}
public void lerMultiplicarESalvar() throws FileNotFoundException, IOException {
List<String> linhas = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(pathSoma.toString()))) {
String line = null;
while ((line = reader.readLine()) != null) {
String[] itens = line.split(";");
int n1 = Integer.parseInt(itens[0]);
int n2 = Integer.parseInt(itens[1]);
int multiplicacao = n1*n2;
linhas.add(getLinha(n1, n2, multiplicacao));
}
}
Files.write(pathMultiplicacao, linhas, StandardOpenOption.CREATE);
}
}