将一个字符串写入文件

时间:2011-08-10 22:13:18

标签: java writetofile

我有上面的代码。我想做的是在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文件,但它没有写入字符串。关于我的bug的任何想法??

2 个答案:

答案 0 :(得分: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。就个人而言,我喜欢明白这一点。)

答案 1 :(得分:1)

写完之后关闭PrintWriter

out1.close();