-1

Two final arrays have to be written to a .txt file, so that you get the first object in one array and the first object in the second array written one after another. Trying to write to text files confuses me enough as it is, but having to write two arrays one after another...

So if array 1 had "A, B, C" and the second had "1, 2, 3", the final output would be
- A 1
- B 2
- C 3

I feel like it would have something to do with making a File and the System.out command, but I'm not sure how to do it...

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
Xili Rem
  • 23
  • 5

3 Answers3

1

Simple.

First question, how would you print that to STDOUT?

assert (one.length == two.length);
for (int i = 0; i < one.length; ++i) {
    System.out.println(one[i] + " " + two[i]);
}

So, now all you need to do is put that into a file. System.out is just a PrintWriter so we need one of those that points to a file:

final Path path = Paths.get("path", "to", "file");
try (final PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path, StandardOpenOption.CREATE_NEW))) {
    for (int i = 0; i < one.length; ++i) {
        writer.println(one[i] + " " + two[i]);
    }
}
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

You could use a PrintWriter create and write to the file. Assuming that the two arrays are of equal size, you could iterate over the elements of the array and use the [.print(String s)][2] method to print to file.

Finally, do not forget to close the stream when you are done.

npinti
  • 51,780
  • 5
  • 72
  • 96
0

Marge the both Array while writing it to file or console.

Like -

String[] array1 ={"A","B","C"};
String[] array2 ={"1","2","3"};

try(PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8")){

    for(int i=0;i<array1.length;i++){
        // add condition if both array are not same in size
        String temp = array1[i]+" "+array2[i]; 
        System.out.println(temp); // console
        writer.println(temp);  // file
    }
    writer.flush();
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • Please always use `try-with-resources` in examples. Calling `close()` directly is bad practice. Calling `flush()` is unnecessary. – Boris the Spider Oct 10 '14 at 07:21
  • Not exactly flush is required for PrintWriter implementation as `close` method does not call internally, check the code please – Subhrajyoti Majumder Oct 10 '14 at 07:25
  • Wrong, `PrintWriter.close()` closes the writer that it decorates. In your case a `BufferedWriter`. _that_ writer flushes itself. Why would a `PrintWriter` call `flush` on close? It's not necessarily buffered... – Boris the Spider Oct 10 '14 at 08:07