简体   繁体   English

如何使用Printwriter将String数组写入Java中的文本文件?

[英]How do I write String arrays to a text file in java using Printwriter?

I need help writing some contents of array objects (following are two example of arrays I'm using) to a text file using Printwriter. 我需要帮助,使用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","","");

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: 如果您想知道如何编写数组中包含的对象的所需特征,可以重写自定义类的toString()方法:

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;
    }
}

PrintWriter admits a String , so you can override toString() method in Astronauts class, and then iterate over 1-D or 2-D dimenssional array: PrintWriter接受String ,因此您可以覆盖Astronauts类中的toString()方法,然后遍历一维或二维维数组:

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 2维

     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 不要忘记flush()close() PrintWriter

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. 这不仅可以创建文件,而且还可以采用表格格式将其写入文件,而无需覆盖toString()方法。

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. 由于您的数组内容都是同一类的Passengers ,如果您对默认的Array.toString格式不满意,我将在Passengers中创建一个toString()方法,该方法返回所需的字符串表示形式。

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 . 注意:正如其他人提到的那样,我将Astronauts变量重命名为小写的astronauts I'd also rename the Passengers class to Passenger . 我还将Passengers类重命名为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. 或者,您可以提供完整的文件路径,例如C:/Users/Me/directory/output.txt但是在这种情况下,您需要确保目录路径已经存在。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM