簡體   English   中英

將對象寫入文件輸出

[英]Writing Object to File Output

我只是想將輸出寫入File,並且正在使用FileWriter

File file = new File("data.txt");
FileWriter output = null;

try
{
    Scanner scanner = new Scanner(file);
    output = new FileWriter("Output.txt");
    ....

因此,當我編寫String結果時,它只是:

output.write("CONFIRMED ");

但是如何打印對象?

output.write(student);

我最初在類中使用student.print()

對於Student班:

public void print()
{
    System.out.print(studentID + " "  + studentName + " ");
}

對於Node類:

public void print()
{
    item.print();
    if(next != null)
    {
       next.print();
    }
}

我也必須將FileWriter導入這些類嗎? 我當時正在考慮將print()方法轉換為toString()方法,但是我不確定如何為Node類更改它,因為它在內部使用了print()方法。

您可以泛化Student.print()Node.print()並讓他們接受PrintWriter

 public class Student {
     public void print(PrintWriter out) {
          out.print(studentID + " "  + studentName + " ");
     }
 } 

然后它們更加有用,並且與System.out無關。 這樣,您可以創建一個包裝FileWriterPrintWriter並調用這些打印方法:

PrintWriter out = new PrintWriter(new FileWriter("Output.txt"));
...
student.print(out);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM