How do I save an array to a . txt file in Java the same way it appears in the console?

Asked

Viewed 224 times

0

I made a code that generates a square matrix N x N with random numbers. So far ok. I made a method to record this matrix in a file .txt, only that the matrix simply comes out with random values, even though I do the conversion of the whole matrix structure int for String.

Follow the main class:

import java.util.Scanner;
import java.util.Random;
import java.io.IOException;

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    System.out.print("De o valor para dimensão de uma matriz quadrada: ");
    int N = in.nextInt();
    int [][] matrix1 = new int[N][N];
    //double [][] matriz2 = new double[N][N];
    Random rand = new Random(); 
    rand.setSeed(System.currentTimeMillis()); 
    for (int i = 0 ; i < N ; i++) {     
        for (int j = 0 ; j < N ; j++) {
            Integer r = rand.nextInt()% 1000; 
            matrix1[i][j] = Math.abs(r);
        }
    }
    System.out.println("A matriz quadrada gerada de tamanho " + N + " foi:");
    printMatrix graph = new printMatrix();
    graph.printGraph(matrix1, N);
    graph.matrixToFile(matrix1);
}

So I made a class with two methods:

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class printMatrix {
    public void printGraph(int[][] array, int n) {
        for (int i = 0; i < n; i++) {  
            System.out.print("[");   
            for (int j = 0; j < n; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println("]");
        }
        System.out.print("\n");   
    }

    public void matrixToFile(int[][] array) throws IOException {
        FileWriter arqMatrix = new FileWriter("Matriz 1.txt");
        PrintWriter gravarArq = new PrintWriter(arqMatrix);
        gravarArq.println(Arrays.toString(array));
        arqMatrix.close();
        System.out.println("Arquivo 'Matriz 1.txt' no mesmo local do projeto.\n");
    }
}

So far so good. The problem is when I do this function "gravarArq.println(Arrays.toString(array));". It gets random characters, like in bytes, like: [[I@28d93b30, [I@1b6d3586, [I@4554617c] (in case of placing 3, it always generates this depending on how the "N".

If you put a System.out.println(Arrays.toString(array)); you generate these random values on the console itself, or place a + "teste" at the end of gravarArq.println(Arrays.toString(array)); getting gravarArq.println(Arrays.toString(array) + "teste"); There will be a "test" at the end of the file, that’s how I realized that is not recording in bin/bytes. I don’t mean even by skipping the lines, but because these values are coming out like this.

I would also like to know how to skip lines and format exactly as in the console.

  • Just switch where you used System.out.println for handler.write() (assuming you are using Filewriter), since you have assembled a method that solves item by item an array rather than using Arrays.toString

1 answer

0


Oops, all right? So, basically you made a mistake when printing the Array for recording. One missing for to go through your Array.

All you had to do was make a small addition, using a code that you yourself already had.

printMatrix.java

public void matrixToFile(int[][] array, int n) throws IOException{
    FileWriter arqMatrix = new FileWriter("Matriz 1.txt");
    PrintWriter gravarArq = new PrintWriter(arqMatrix);

    for (int i = 0; i < n; i++){  
        gravarArq.println("[");   
        for (int j = 0; j < n; j++){
            gravarArq.println(array[i][j]);
        }
        gravarArq.println("]");
    }gravarArq.println("\n"); 

    arqMatrix.close();
    System.out.println("Foi gerado um arquivo 'Matriz 1.txt' no mesmo local do projeto.\n");
}

And, as we are now passing the parameter the value of n is needed by him in the call of the method also.

classePrincipal.java

graph.matrixToFile(matrix1, N);

I didn’t do all the work for you, you’ll see that the indentation in the notebook is still "wrong". But this one I’ll leave for you to break your head a little bit. I hope I helped!

  • Wow, you’ve helped enough, man! Now I turn around here with the haha-worth formatting! But I was still doubtful why I was generating those random characters... You would know to answer me?

  • With precision in speech, you wouldn’t know. But my guess is that you were calling the Array and, by not going through it, received as a response the name of each item within it. As if it were a kind of ID for each space within the matrix.

  • Oh I get it... Anyway, I already solved the problem there xD I wish if that was the job, I’ll have to normalize and do her operations with threads, I’ll have to do a second matrix yet

Browser other questions tagged

You are not signed in. Login or sign up in order to post.