3

I have a task which involves passing array values (writing) into a text (.txt) file in Java. This is my first time using BufferedWriter and I've tried quite a few variations on if statements, but can't see to get my program to write in the format matrix[i][j] + "," until it hits the last column index and writes without the comma after the integer.

I tried using the append() method that BufferedWriter extends but I don't think I used it correctly.

Current Code

void writeMatrix(String filename, int[][] matrix) {
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                    bw.write(matrix[i][j] + ",");
            }
            bw.newLine();
        }
        bw.flush();
    } catch (IOException e) {}
}

Current Output

1,2,3,
4,5,6,
7,8,9,

I need the last digit on each line to not include the comma and BufferedWriter apparently doesn't like to add two write() methods together on the same line. So how could I do this?

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Cyka bLyat
  • 35
  • 1
  • 5
  • The phrasing "passing an array into a txt file" is awkward. Passing refers to handing a value or reference, often to a memory-resident data structure, to another process or routine, eg. passing arguments. You don't "pass" a data structure to a persistent store such as a file. – scottb Nov 07 '15 at 03:23

5 Answers5

1

You can change your innermost for loop to this:

for (int j = 0; j < matrix[i].length; j++) {
    bw.write(matrix[i][j] + ((j == matrix[i].length-1) ? "" : ","));
}

This puts a simple ternary operator in that does this:

if j is last index:

  • print nothing ()

else

  • print a comma (,)

On request, this would be the equivalent to this if-else statement:

for (int j = 0; j < matrix[i].length; j++) {
    if(j == matrix[i].length-1) {
        bw.write(matrix[i][j]);
    } else {
        bw.write(matrix[i][j] + ",");
    }
}
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
  • That worked! But I'm not sure I understand the syntax behind the question mark and colon, I haven't seen them used before? – Cyka bLyat Nov 07 '15 at 03:13
  • It's essentially a shortened `if-else` statement. I'll put a simpler alternative up for you. – Jonathan Lam Nov 07 '15 at 03:16
  • And welcome to the SO community (don't worry, your post was formatted ok)! I'm glad I helped (don't forget to accept), and have a good day! – Jonathan Lam Nov 07 '15 at 03:16
0

Compare matrix[i].length with j, then determine to print "," or not.

Intae Kim
  • 309
  • 1
  • 5
0

You just simply add a if-else statement to decide to print the comma or not.

Hope this help!

xxx
  • 3,315
  • 5
  • 21
  • 40
0

You can try adding the if statement inside the iteration. if j is in the last column, it doesnt print the comma to your file, otherwise it does.

void writeMatrix(String filename, int[][] matrix) {
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if(j == matrix[i].length - 1){    
                    bw.write(matrix[i][j]);
                } else{
                    bw.write(matrix[i][j] + ",");
                }        
            }
            bw.newLine();
        }
        bw.flush();
    } catch (IOException e) {
        //why does the catch need its own curly?
    }
}

Hope it works!.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
0

This is an alternative that uses the (really powerful) Java Streams API. For your case, the Collectors.joining() method comes in handy. It only inserts delimiters between elements, so by default you don't get the trailing comma.

void writeMatrix(String filename, int[][] matrix) {
  try {
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

    for (int[] row: matrix) {
      String rowString = Arrays.stream(row)
          .boxed()
          .map(Objects::toString)
          .collect(Collectors.joining(","));
      bw.write(rowString);
      bw.newLine();
    }

    bw.flush();
  } catch (IOException e) {}
}

Note: you could replace the outer for loop with another Streams API call: take a look at forEach in the docs. And there are many examples you can find online too.

void writeMatrix(String filename, int[][] matrix) {
  String matrixString = Arrays.stream(matrix).map(row ->
      Arrays.stream(row)
          .boxed()
          .map(Objects::toString)
          .collect(Collectors.joining(","))
      )
      .collect(Collectors.joining("\n"));

  try {
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
    bw.write(matrixString);
    bw.flush();
  } catch (IOException e) {}
}

The Streams API is really elegant. The only issue you might find with this implementation is a stack overflow (excuse the pun :)) if the matrix is too large.

ATutorMe
  • 820
  • 8
  • 14