0

I need help writing some contents of array objects (following are two example of arrays I'm using) to a text file using Printwriter. Any ideas? I'm a beginner, so the simpler the better, thanks!

Astronauts[0][0] = new Passengers(-1, "", 1, 0, 0, "", "", 0, "", "", "", "", ""); 

Astronauts[0][1] = new Passengers(0, "Pilot", 2424, 14, 0, "Bruce", "Banner", 0, "678-884-6325", "Mom", "678-884-6323","","");

Astronauts[0][2] = new Passengers(0, "Pilot", 1248, 3, 0, "Sally", "Forth", 0, "678-921-1135", "Hannah", "678-921-1130","","");


 Astronauts[1][0] = new Passengers(-1, "", 2, 0, 0, "", "", 0, "", "", "", "", "");

Astronauts[1][1] = new Passengers(0, "Pilot", 1022, 55, 0, "Buz", "Aldrin", 0, "404-014-4553", "June", "404-014-4555","","");

Astronauts[1][2] = new Passengers(0, "Pilot", 2813, 8, 0, "Alice", "Dyer", 0, "678-884-6325", "Mom", "678-884-6323","","");

4 Answers 4

2

I'm not sure if I'm catching your problem correctly, because writing the contents of an array to a file is pretty straight-forward:

String[] arr = {"a", "b", "c"};
try {
    PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
    pw.println(Arrays.toString(arr));
    pw.flush();
    System.out.println("Finished");
} catch (IOException e) {
    e.printStackTrace();
}

[EDIT]

I realise I may not have addressed your entire problem. If you are wondering how to write the desired traits of the objects contained in an array, you can override the toString() method of your custom class:

class A {
    public static void main(String[] args) {
        B[] bs = {new B("a", "b"),
                  new B("c", "d"),
                  new B("e", "f"),
                  new B("g", "h")};

        try {
            PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
            for (B b : bs) {
                pw.println(b);
            }
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Finished");
    }
}

class B {
    private String prop1;
    private String prop2;

    public B (String prop1, String prop2) {
        this.prop1 = prop1;
        this.prop2 = prop2;
    }

    @Override
    public String toString() {
        return this.prop1 + " " + this.prop2;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since your array contents are all of the same class Passengers, if you're not happy with the default Array.toString format I'd create a toString() method in Passengers that returns your desired string representation.

Then:

try {
       PrintWriter printWriter = new PrintWriter(new FileWriter("output.txt"));

       for(Passengers[] passengers: Astronauts) {
           for(Passengers passenger: passengers) {
                printWriter.println(passenger);
           }
       }

       printWriter.close();  // no need to flush, since close() does it anyway.

   } catch (IOException e) {
       e.printStackTrace();
   }

Note: As others have mentioned, I'd rename the Astronauts variable to be lowercase astronauts. I'd also rename the Passengers class to Passenger.

Edit: Using the above code the output file should appear in the working directory where you are running the program from. Alternatively you can supply a full file path such as C:/Users/Me/directory/output.txt but in that case you need to make sure the directory path already exists.

Yet another alternative is to modify the code to automatically create the path for you:

    File file = new File ("C:/Users/Me/directory/output.txt");
    file.getParentFile().mkdirs();
    PrintWriter printWriter = new PrintWriter(file);

2 Comments

ok, so I used this code but adapted it to the whole file and I'm still not seeing a text file. Shouldn't one pop up on its own?
Yes the above code should create the file for you. I've edited the answer with some explanation in this regard. Hope it helps.
0

Here is how you might want to do it.

String twoDArray[][] = {{"one","two"},{"one","two"},{"one","two"}};
    String filePath = "C:/Users/arjun.lajpal/Desktop/dummyFile.txt";
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(filePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    writer.printf("%20s%20s","Astraunauts","Passengers");
    writer.println();
    for(int i=0;i<twoDArray.length;i++){
        for(int j=0;j<twoDArray[i].length;j++)
            writer.printf("%20s",twoDArray[i][j]);

        writer.println();

        }
    writer.flush();
    writer.close();

This not only will make your file but also write to the file in a nice tabular format without any need to override toString() method.

Comments

0

PrintWriter admits a String, so you can override toString() method in Astronauts class, and then iterate over 1-D or 2-D dimenssional array:

By the way, variable names should start with lowercase character.

  • 1-D

    for (int i = 0; i < astronauts.length; i++) { 
        pw.print(Arrays.toString(astronauts[i]); 
    } 
    
  • 2-D

    for (int i = 0; i < astronauts.length; i++) {
        for (int j = 0; j < astronauts[i].length; i++) {
            pw.print(astronauts[i][j]); 
        } 
    } 
    

Don't forget to flush() and close() PrintWriter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.