Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Grave uma sequência de 500 números aleatórios em um arquivo txt, leia esse arquivo txt e faça a ordenação desses
- * números, utilize qualquer método de ordenação que quiser, grave em um novo txt o resultado.
- */
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.PrintWriter;
- public class Gravar {
- private static BufferedReader lerArq;
- private static int maxNumeros = 7;
- private static int[] numeros = new int[maxNumeros];
- public static void main(String[] args) throws IOException {
- gravar(numerosAleatorios(), "num_des.txt");
- int[] numeros = ler("num_des.txt");
- int[] ordenados = ordenacao(numeros);
- gravar(ordenados, "num_ord.txt");
- }
- public static int[] numerosAleatorios(){
- int[] numeros = {10,20,1,2,5,10,58};
- return numeros;
- }
- public static int[] ler(String nome) throws IOException{
- FileReader arq;
- try {
- arq = new FileReader(nome);
- lerArq = new BufferedReader(arq);
- int i = 0;
- String arqu = lerArq.readLine();
- while (arqu != null) {
- numeros[i] = Integer.parseInt(arqu);
- i++;
- arqu = lerArq.readLine();
- }
- return numeros;
- } catch (FileNotFoundException e) {
- System.out.printf(e.getMessage());
- }
- return null;
- }
- public static void gravar(int numeros[], String nome){
- for(int i = 0; i < (numeros.length); i++){
- try{
- FileWriter arq;
- if(i == 0){
- arq = new FileWriter(nome);
- }else{
- arq = new FileWriter(nome, true);
- }
- PrintWriter gravarArq = new PrintWriter(arq);
- if(i == maxNumeros - 1){
- gravarArq.printf(Integer.toString(numeros[i]));
- }else{
- gravarArq.printf(numeros[i] + "\n");
- }
- arq.close();
- }catch(IOException e){
- System.out.printf(e.getMessage());
- }
- }
- }
- public static int[] ordenacao(int v[]){
- for (int i = v.length; i >= 1; i--) {
- for (int j = 1; j < i; j++) {
- if (v[j - 1] > v[j]) {
- int aux = v[j];
- v[j] = v[j - 1];
- v[j - 1] = aux;
- }
- }
- }
- return v;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment