write a string into file

£可爱£侵袭症+ 提交于 2019-12-10 23:26:09

问题


I have the above code. What i wanna do is to write in a txt file a string.

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

The above code creates a txt file but it doesnt write the string to it. Any idea about my bug??


回答1:


You're not closing or flushing the PrinterWriter or the FileWriter. So basically it's being buffered, so nothing is being written to the file.

You should close both in finally blocks:

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

Closing will flush automatically.

(I can't remember - it's likely that closing the PrintWriter will close the FileWriter. Personally I like to be explicit about it anyway.)




回答2:


Close the PrintWriter after you're done writing to it:

out1.close();


来源:https://stackoverflow.com/questions/7018541/write-a-string-into-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!