2

我有上面的代码。我想做的是在一个txt文件中写一个字符串。

     import java.io.*;
    import java.util.*;

    public void writeAsfalizomenos(asfalizomenos myObj) throws IOException {

    Scanner scanner = new Scanner(System.in);
    System.out.print("Surname: ");
    String username = scanner.nextLine();
    System.out.println(username);


    FileWriter outFile = new FileWriter("asdf.txt", true);
    PrintWriter out1 = new PrintWriter(outFile);

    out1.append(username);
    out1.println();
    out1.append("adfdas");



    //
    // Read string input for username
    //



}

public static void main(String [] args) throws IOException{


    asfalizomenos a = new asfalizomenos();
    a.writeAsfalizomenos(a);
}

上面的代码创建了一个 txt 文件,但它没有将字符串写入其中。关于我的错误的任何想法?

4

2 回答 2

6

您没有关闭或刷新PrinterWriterFileWriter。所以基本上它被缓冲了,所以没有任何东西被写入文件。

您应该在 finally 块中关闭两者:

FileWriter outFile = new FileWriter("asdf.txt", true);
try {
    PrintWriter out1 = new PrintWriter(outFile);
    try {
        out1.append(username);
        out1.println();
        out1.append("adfdas");
    } finally {
       out1.close();
    }
} finally {
   outFile.close();
}

关闭将自动冲洗。

(我不记得了 - 关闭 可能PrintWriter会关闭FileWriter。我个人还是喜欢明确说明这一点。)

于 2011-08-10T22:14:44.547 回答
1

PrintWriter写完后关闭它:

out1.close();
于 2011-08-10T22:15:02.387 回答